mysql jdbc 批量_MYSQL 之 JDBC(十四):批量处理JDBC语句提高处理效率
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);
}
}
}
總結
以上是生活随笔為你收集整理的mysql jdbc 批量_MYSQL 之 JDBC(十四):批量处理JDBC语句提高处理效率的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql connector c 源码
- 下一篇: shell mysql t e_shel