JDBC用到的批处理的方法
1、addBatch(String):添加需要批量处理的SQL语句或是参数;
2、executeBatch():执行批量处理语句;
3、clearBatch():清空缓存的数据
批处理操作
此处使用的jar包为5.1.37 jar包不同,对于批处理的支持程度不同。
1、开启批处理
#url=jdbc:mysql:///orcl?rewriteBatchedStatements=true&useServerPrepStmts=false
代码:
public void testUseBatch() throws Exception {
// 1.获取连接
Connection connection = JDBCUtils.getConnection();
// 2.访问数据库
PreparedStatement statement = connection.prepareStatement("insert into admin values(null,?,?)");
for (int i = 1; i < 50000; i++) {
statement.setString(1, "小花" + i);
statement.setString(2, "8888");
// 批处理
statement.addBatch();// 将要执行的sql语句添加到批处理包(装篮子的操作)
if (i % 1000 == 0) {
statement.executeBatch();// 提交批处理的命令们(上楼运篮子的操作)
statement.clearBatch();// 清空批处理包(卸篮子的操作)
} else if (i > 49000) {
statement.executeBatch();// 提交批处理的命令们(上楼运篮子的操作)
statement.clearBatch();// 清空批处理包(卸篮子的操作)
}
}
// 3.关闭
JDBCUtils.closeConnection(null, statement, connection);
}