预处理语句对象 PreparedStatement
String sql = "delete from ajia_user where id=?";
PreparedStatement pstmt
= conn.prepareStatement(sql);
如果删除10条数据,与数据库交互10次
for(int id:ids){
pstmt.setInt(1,id);
//将操作添加到语句列表中
pstmt.addBatch();
//pstmt.executeUpdate();
//一次性缓存一组数据
在语句对象中,维护了一个语句列表
}
//一次性执行一组操作
pstmt.executeBatch();
addBatch(),填充语句列表
executeBatch(),执行语句列表
clearBatch(),清除语句列表
public class JdbcDemo1 {
public static void main(String[] args) {
int[] ids = {70,71};
String sql = "DELETE FROM ajia_user WHERE id=?";
Connection conn = null;
boolean autoCommit = false;
try { conn = JdbcUtil.getConn();
autoCommit = conn.getAutoCommit();
conn.setAutoCommit(false);
PreparedStatement pstmt = conn.prepareStatement(sql);
for(int id:ids){
pstmt.setInt(1, id);
//添加到语句列表中
pstmt.addBatch();
}
//执行语句列表 pstmt.executeBatch();
//默认JDBC自动给数据库发送commit指令 conn.commit();
//关闭语句对象
pstmt.close();
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
} e.printStackTrace();
}finally{ try {
conn.setAutoCommit(autoCommit);
} catch (SQLException e) {
e.printStackTrace();
} JdbcUtil.close(conn); } } }