假设一个情景,将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");
}
}