Java 使用JDBC案例
目录
1、编写工具类
package JDBC.units; import java.io.InputStream; import java.sql.*; import java.util.Properties; /** * @author shkstart * @create 2022-02-10 11:07 **/ public class JdbcUnits { private static String driver=null; private static String url=null; private static String userName=null; private static String passWord=null; static { try{ InputStream in = JdbcUnits.class.getClassLoader().getResourceAsStream("db.properties"); Properties properties = new Properties(); properties.load(in); driver = properties.getProperty("driver"); url = properties.getProperty("url"); userName = properties.getProperty("userName"); passWord = properties.getProperty("passWord"); //驱动只加载一次 Class.forName("com.mysql.jdbc.Driver"); } catch (Exception e) { e.printStackTrace(); } } //获取连接 public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url, userName, passWord); } //释放连接 public static void close(Connection cn, ResultSet re, Statement st){ try { if (cn != null) { cn.close(); } if (re != null) { re.close(); } if (st != null) { st.close(); } }catch(Exception e){ e.printStackTrace(); } } }
2、增加测试
package JDBC; import JDBC.units.JdbcUnits; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; /** * @author shkstart * @create 2022-02-10 11:46 **/ public class TestInsert { public static void main(String[] args) throws SQLException { PreparedStatement pre = null; Connection conn = null; try { conn = JdbcUnits.getConnection(); String sql = "INSERT INTO USER(NAME,account,PASSWORD) VALUES (?,?,?);"; pre = conn.prepareStatement(sql); pre.setString(1,"王建鹏"); pre.setInt(2, 515151); pre.setString(3,"21515615"); int i = pre.executeUpdate(); if (i > 0){ System.out.println("插入成功"); } }catch(Exception e){ e.printStackTrace(); }finally{ if (pre != null){ pre.close(); } if (conn != null){ conn.close(); } } } }