什么是JDBC批处理
JDBC批处理是指,批量运行数据库的增删改查操作。
例如:当需要对数据库进行大量的数据插入操作时,如果一条一条的数据插入速度非常缓慢,这个时候就需要使用到批处理技术,将插入数据的操作进行积攒,当达到设置的指定数量时进行一次插入所有批次数据,这样做会大大减少对数据库访问所消耗的时间。
操作演示
我们模拟大量的数据插入操作,使用循环对数据库插入10万条数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
@Test public void test() throws SQLException { Connection connection = JDBCUtils.getConnection();
String sql = "insert into student values(?, ?, ?);";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
long startTime = System.currentTimeMillis(); for (int i = 1; i <= 100000; i++) { preparedStatement.setInt(1, i); preparedStatement.setString(2, "value"+i); preparedStatement.setInt(3, 100+i);
preparedStatement.executeUpdate(); }
long endTime = System.currentTimeMillis(); System.out.println("一共花费了" + (endTime - startTime) + "毫秒"); JDBCUtils.close(connection, preparedStatement); }
|
清空并查看数据库数据:
1 2
| delete from student; select count(*) from student;
|

运行代码开始插入数据。经过285826毫米才完成数据的插入工作。

在数据库中查看数据是否插入成功。
1
| select count(*) from student;
|
数据插入成功。

要想使用批处理操作首先需要修改配置文件。如下所示。

代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
@Test public void test2() throws SQLException { Connection connection = JDBCUtils.getConnection();
String sql = "insert into student values(?, ?, ?);";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
long startTime = System.currentTimeMillis(); for (int i = 1; i <= 100000; i++) { preparedStatement.setInt(1, i); preparedStatement.setString(2, "value"+i); preparedStatement.setInt(3, 100+i);
preparedStatement.addBatch();
if (i % 1000 == 0){ preparedStatement.executeBatch(); preparedStatement.clearBatch(); } } long endTime = System.currentTimeMillis(); System.out.println("一共花费了" + (endTime - startTime) + "毫秒"); JDBCUtils.close(connection, preparedStatement); }
|
清空并查看数据库数据:
1 2
| delete from student; select count(*) from student;
|

运行代码开始插入数据。可以看到仅花费了1182毫秒数据就插入完成。

在数据库中查看数据是否插入成功。
1
| select count(*) from student;
|
数据插入成功。
