文章目录
重点:一个Connection对象就是一个事务
不考虑事务
public Integer commonUpdate(String sql, Object... args) {
Connection conn = null;
PreparedStatement pStatement = null;
Integer updateRow = null;
try {
// 1. 获取连接
conn = ConnectionTest.getConnection2();
// 2. 预编译sql语句
pStatement = conn.prepareStatement(sql);
// 3. 填充sql占位符
for (int i = 0; i < args.length; i++) {
pStatement.setObject(i + 1, args[i]);
}
// 4. 执行sql语句
updateRow = pStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 5. 关闭资源
ConnectionTest.closeResource(conn, pStatement, null);
}
return updateRow;
}
考虑事务 – 最终版
public int commonUpdate(Connection conn, String sql, Object... args) {
PreparedStatement ps = null;
int rowNumber = 0;
try {
// 1. 预编译SQL语句
ps = conn.prepareStatement(sql);
// 2. 填充SQL语句的占位符
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
// 3. 执行SQL语句
rowNumber = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
// 4. 关闭资源,但不关闭Connection、由方法调用者自行关闭
ConnectionTest.closeResource(null, ps, null);
return rowNumber;
}