封装数据库连接和关闭操作
@Test
public void testUpdate() throws Exception{
//1、获取数据库连接
Connection conn= JDBCUtils.getConnection();
// 2、预编译sql语句,返回PreparedStatement的实例
String sql="update customers set name=? where id=?";
PreparedStatement ps=conn.prepareStatement(sql);
// 3、填充占位符
ps.setObject(1,"hahaha!!!!!");
ps.setObject(2,21);
// 4、执行
ps.execute();
// 5、资源的关闭
JDBCUtils.closeResource(conn,ps);
}
public class JDBCUtils {
public static Connection getConnection() throws Exception{
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");
Class.forName(driverClass);
Connection conn= DriverManager.getConnection(url,user,password);
return conn;
}
public static void closeResource(Connection conn,Statement ps){
try{
if(ps!=null)
ps.close();
} catch (SQLException e){
e.printStackTrace();
}
try{
if(conn!=null)
conn.close();
}catch (SQLException e){
e.printStackTrace();
}
}
}