之前的更新方法
public static void update(String sql) {
Connection conn = null;
Statement statement = null;
try {
conn = JDBCTools.getConnection();
statement = conn.createStatement();
statement.executeUpdate(sql);// attention。。。
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCTools.close(statement, conn);
}
}
}
升级后的方法:
/**
* 写一个通用的更新方法 包括 INSERT DELETE UODATE 使用工具类
* 执行SQL语句,使用PreparedStatement
*
* @param sql
* @param args:填写SQL占位符放入可变参数
*/
public static void update(String sql, Object... args) {
// 可变参数数组
Connection conn = null;
PreparedStatement preparedstatement = null;
try {
conn = JDBCTools.getConnection();
preparedstatement = conn.prepareStatement(sql);
//数组使用for循环,填充占位符!!!
for (int i = 0; i < args.length; i++) {
preparedstatement.setObject(i + 1, args[i]);
}
preparedstatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCTools.close(preparedstatement, conn);
}
}