mysql jdbc 批量_MYSQL 之 JDBC(十四):批量处理JDBC语句提高处理效率

本文通过Java的JDBC展示了两种向数据库批量插入10w条记录的方法:使用Statement和PreparedStatement。实验结果显示,使用PreparedStatement并配合批量处理可以显著提高数据插入效率。
摘要由CSDN通过智能技术生成

packagecom.litian.jdbc;importjava.sql.Connection;importjava.sql.PreparedStatement;importjava.sql.Statement;/***@author: Li Tian

* @contact: [email protected]

* @software: IntelliJ IDEA

* @file: JDBCTest4.java

* @time: 2020/4/4 14:18

* @desc: |批量处理事务*/

public classJDBCTest4 {public static voidmain(String[] args){//testStatement();

testPrepareStatement();

}/*** 向数据库的数据表中插入10w条记录

* 测试如何插入,用时最短

* 1. 使用Statement:15038*/

public static voidtestStatement() {

Connection conn= null;

Statement st= null;

String sql= null;try{

conn=JDBCTools.getConnection();

JDBCTools.beginTx(conn);

st=conn.createStatement();long begin =System.currentTimeMillis();for (int i = 0; i < 100000; i++) {

sql= String.format("insert into t_user2(username, pwd) values(name_%d, 6666)", i);

st.executeUpdate(sql);

}long end =System.currentTimeMillis();

System.out.println(end-begin);

JDBCTools.commit(conn);

}catch(Exception e) {

e.printStackTrace();

JDBCTools.rollback(conn);

}finally{

JDBCTools.release(null, st, conn);

}

}/*** 向数据库的数据表中插入10w条记录

* 测试如何插入,用时最短

* 2. 使用PreparedStatement:13131

* 3. 在2的基础上使用批量处理:24596?这就很尴尬了*/

public static voidtestPrepareStatement() {

Connection conn= null;

PreparedStatement st= null;

String sql= null;try{

conn=JDBCTools.getConnection();

JDBCTools.beginTx(conn);

sql= "insert into t_user2(username, pwd) values(?,?)";

st=conn.prepareStatement(sql);long begin =System.currentTimeMillis();for (int i = 0; i < 100000; i++) {

st.setString(1, "name_" +i);

st.setString(2, "6666");

st.executeUpdate();//“积攒”sql语句

st.addBatch();;//当积攒到一定程度,就统一地执行一次,并且清空先前积攒的sql

if((i + 1) % 300 == 0){

st.executeBatch();

st.clearBatch();

}

}//若总条数不是批量数值的整数倍,则还需要额外再执行一次

if(100000 % 300 != 0){

st.executeBatch();

st.clearBatch();

}long end =System.currentTimeMillis();

System.out.println(end-begin);

JDBCTools.commit(conn);

}catch(Exception e) {

e.printStackTrace();

JDBCTools.rollback(conn);

}finally{

JDBCTools.release(null, st, conn);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值