JDBC 批处理
批处理允许将相关的SQL语句分组到批处理中,并通过对数据库的一次调用提交它们。
当一次访问数据库可以提交多个SQL 语句的时候,能够很大程度减轻连接数据库的开销,从而提高性能。
那么如何实现使用批处理,完成SQL语句的整合,下面开始介绍
1. Statement 批处理
以下是使用语句对象的批处理的典型步骤序列。
-
使用 createStatement() 方法创建statement对象
-
使用 setAutoCommit() 将 auto-commit 设置为false;
-
使用 addBatch() 方法在创建语句对象上添加要用到的SQL语句到批处理中。
-
在创建的语句对象上使用 executeBatch() 方法执行所有SQL 语句
-
最后,使用 commit() 方法提交所有更改
使用批处理需要先创建好statement对象或者是PreparedStatement 预处理对象
connection = DriverManager.getConnection(url,username,userpass);
//设置为手动提交
connection.setAutoCommit(false);
// 创建好 statement 对象,
statement = connection.createStatement();
//开始写批处理
String SQL1 = "select * from emp2";
statement.addBatch(SQL1); // 通过 addBatch 添加
String SQL2 = "insert into emp2(stuid,stuname) value("1","张三");
statement.addBatch(SQL2);
// 执行
int[] ints = statement.executeBatch(); // 得到执行 受影响行数
// 提交
connection.commit();
for(int anInt : ints){
System.out.println("anInt:"+anInt);
}