jdbc batch批量处理与非批量的比较

本文通过一个示例展示了在处理50万条数据插入数据库时,使用JDBC的batch批量处理与非批量处理的效率差异。批量处理在1分钟内完成,而非批量处理则耗时较长,凸显了批量操作的优越性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

假设一个情景,将50万条数据插入数据库一张表中,测试一下使用batch批量和不使用批量的效率问题。其中红色字体部分为batch批量处理,大概处理50万条数据1分钟以内,而蓝色字体为非批量处理,大概处理几千条数据就需要一分钟

import java.text.SimpleDateFormat;
import java.util.Date;


import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;


public class Cetest{
public static void main(String args[]) throws SQLException{
Date now = new Date(); 
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String begin = dateFormat.format(now);
long startTime = System.currentTimeMillis();    //获取开始时间
System.out.println("开始执行时间是:"+begin);
String url = "jdbc:mysql://127.0.0.1:3306/mysql?user=root&password=88888888&useUnicode=true&characterEncoding=UTF8";

try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection(url);
con.setAutoCommit(false);
String sql = "insert into testTable values (?,?)";
PreparedStatement  stm =  (PreparedStatement) con.prepareStatement(sql);
/*for(int i = 0 ; i<500000 ; i++){
stm.setString(1, i+"");
stm.setString(2, i+""+"---testTable");
stm.addBatch();
}
int[] aa = stm.executeBatch();
con.commit();*/

for(int i = 0 ; i<500000 ; i++){
stm.setString(1, i+"");
stm.setString(2, i+""+"---testTable");
stm.execute();
con.commit();
}


} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String end = dateFormat.format(new Date());
long endTime = System.currentTimeMillis();    //获取结束时间
System.out.println("结束执行时间是:"+end);
System.out.println("一共执行时间是"+(startTime-endTime)/1000+"s");
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值