获取数据库的连接
public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException { // 1、读取配置文件中的4个基本信息 InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties"); Properties pros = new Properties(); pros.load(is); String user = pros.getProperty("user"); String password = pros.getProperty("password"); String url = pros.getProperty("url"); String driverClass = pros.getProperty("driverClass"); // 2、加载驱动 Class.forName(driverClass); // 3、获取连接 Connection conn = DriverManager.getConnection(url, user, password); return conn; }
关闭连接和Statement的操作
public static void closeResource(Connection conn, PreparedStatement ps) { try { if (ps != null) ps.close(); } catch (SQLException e) { e.printStackTrace(); } try { if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } }
修改customers表的一条数据
package com.JDBCStudy3.PreparedStatement.crud; import java.sql.Connection; import java.sql.PreparedStatement; import JDBC_util.JDBCutils; public class PreparedStatementUpdateTest { // 修改customers表的一条数据 public void testUpdate() { Connection conn = null; PreparedStatement ps = null; try { // 1、获取数据库的连接 conn = JDBCutils.getConnection(); // 2、预编译sql语句,返回PreparedStatement的实例 String sql = "update customers set name = ? where id = ?"; conn.createStatement(); ps = conn.prepareStatement(sql); // 3、填充占位符 ps.setObject(1, "莫扎特"); ps.setObject(2, 18); // 4、执行 ps.execute(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // 5、资源的关闭 JDBCutils.closeResource(conn, ps); } } }