尚硅谷之JDBC
2、编写通用的增删改查方法
2.1通用的增删改
//通用的更新数据库的方法:insert,update,delete语句时 public static int update(String sql)throws SQLException{ //1、获取连接 Connection conn = JDBCUtils.getConnection();
//2、获取Statement对象,这个对象是用来给服务器传sql并执行sql Statement st = conn.createStatement();
//3、执行sql int len = st.executeUpdate(sql);
//4、释放资源 JDBCUtils.closeQuietly(st, conn);
return len; }
// 通用的更新数据库的方法:insert,update,delete语句,允许sql带? public static int update(String sql, Object... args)throws SQLException{ Connection conn = JDBCUtils.getConnection();
int len = update(conn,sql,args);
JDBCUtils.closeQuietly(conn);
return len; }
// 通用的更新数据库的方法:insert,update,delete语句,允许sql带? public static int update(Connection conn, String sql, Object... args)throws SQLException{ //2、获取PreparedStatement对象,这个对象是用来sql进行预编译 PreparedStatement pst = conn.prepareStatement(sql);
//3、设置sql中的? if(args!=null && args.length>0){ //数组的下标是从0开始,?的编号是1开始 for (int i = 0; i < args.length; i++) { pst.setObject(i+1, args[i]); } }
//4、执行sql int len = pst.executeUpdate();
//5、释放资源 JDBCUtils.closeQuietly(pst);
return len; } |