【数据库编程】6.批处理
1. 基本介绍
- 当需要成批插入或者更新记录时。可以采用Java的批处理机制,这一机制允许多条语句一次性提交给数据库批量处理。通常情况下比单独提交再处理更有效率。
- JDBC连接MySQL时,如果要使用批处理功能,URL中需要添加参数rewriteBatchedStatements=true,如果没有加该参数,即便代码中使用了批处理也不会生效。
- 批处理往往会和PreparedStatement一起搭配使用,即可以减少编译次数,又可以减少运行次数,效率大大提高。
2. 批处理方法
- void addBatch()
- 添加需要批量处理的SQL语句或参数
- int[] executeBatch()
- 执行批量处理
- void clearBatch()
- 清空批处理包
3. 批处理案例
-
使用循环连续插入5000条记录,不使用批处理本机一共花费了8.438s,代码如下:
@Test public void testNoBatch() throws Exception { // 获取值 Properties properties = new Properties(); properties.load(new FileInputStream("src\\mysql.properties")); String user = properties.getProperty("user"); String password = properties.getProperty("password"); String dirver = properties.getProperty("dirver"); String url = properties.getProperty("url"); // 注册驱动 Class.forName(dirver); // 得到连接和PreparedStatement Connection connection = DriverManager.getConnection(url, user, password); PreparedStatement preparedStatement = connection.prepareStatement("insert into demo values(?, ?)"); long start = System.currentTimeMillis(); for (int i = 0; i < 5000; i++) { preparedStatement.setInt(1, i); preparedStatement.setString(2, "alan" + i); preparedStatement.executeUpdate(); } long end = System.currentTimeMillis(); System.out.println("不使用批处理耗时:" + (end - start) / 1000.0 + "s"); }
-
每当有1000条记录时,就执行一次批处理,使用批处理本机一共花费了0.11s,效率提升非常高,减少了网络通信次数和事务提交次数。代码如下:
@Test public void testPatch() throws Exception { // 获取值 Properties properties = new Properties(); properties.load(new FileInputStream("src\\mysql.properties")); String user = properties.getProperty("user"); String password = properties.getProperty("password"); String dirver = properties.getProperty("dirver"); String url = properties.getProperty("url"); // 注册驱动 Class.forName(dirver); // 得到连接和PreparedStatement Connection connection = DriverManager.getConnection(url, user, password); PreparedStatement preparedStatement = connection.prepareStatement("insert into demo values(?, ?)"); long start = System.currentTimeMillis(); for (int i = 0; i < 5000; i++) { preparedStatement.setInt(1, i); preparedStatement.setString(2, "alan" + i); preparedStatement.addBatch(); // 满1000条数据就执行批处理,然后清空 if ((i + 1) % 1000 == 0) { preparedStatement.executeBatch(); preparedStatement.clearBatch(); } } long end = System.currentTimeMillis(); System.out.println("使用批处理耗时:" + (end - start) / 1000.0 + "s"); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)