PreparedStatement实现通用的增删改操作
PreparedStatement实现通用的增删改操作
public void testCommonUpdate() throws Exception {
String sql="update customers set name=? where id=?";
update(sql,"wtf",19);
}
public void update(String sql,Object ...args) throws Exception{
Connection conn=JDBCUtils.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
for(int i=0;i<args.length;i++){
ps.setObject(i+1,args[i]);
}
ps.execute();
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();
}
}
}