批处理的API:
Statement的批处理:
void addBatch(String sql) 把sql添加到缓存区中(没有发送的)
int[] executeBatch() 执行批处理缓存中sql语句(发送到数据库执行)
void clearBatch() 清空缓存区sql语句
PreparedStatement的批处理:
void addBatch() 把参数添加到缓存区中
int[] executeBatch() 执行批处理缓存中所有参数(发送到数据库执行)
void clearBatch() 清空缓存区参数列表
代码演练:
PrepaedStatement执行批处理
public static void testByPreparedStaementBatch(){
Connection conn = null;
PreparedStatement stmt = null;
try{
conn = JdbcUtil.getConnection();
stmt = conn.prepareStatement("INSERT INTO student VALUES(?,?,?,?)");
for(int i=1;i<=2000;i++){
//参数赋值
stmt.setInt(1, i);
stmt.setString(2, "张三");
stmt.setInt(3, 20);
stmt.setString(4, "男");
//把参数添加到缓存区
stmt.addBatch();
//每20次发送一次参数
if(i%20==0){
//执行批处理命令
stmt.executeBatch();
//清空缓存区的参数
stmt.clearBatch();
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
JdbcUtil.close(stmt, conn);
}
}
statement执行批批处理
public static void testByStaementBatch(){
Connection conn = null;
Statement stmt = null;
try{
conn = JdbcUtil.getConnection();
stmt = conn.createStatement();
for(int i=1;i<=2000;i++){
//把sql添加到缓存区
stmt.addBatch("INSERT INTO student VALUES("+i+",'张三',20,'男')");
//每20条发送sql
if(i%20==0){
//执行批处理命令
stmt.executeBatch();
//清空缓存区
stmt.clearBatch();
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
JdbcUtil.close(stmt, conn);
}
}