Java的JDBC的批量提交


package com.fd.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCBatch {

    public static void main(String[] args) {
        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;
        
        try {
            Class.forName("com.mysql.jdbc.Driver");
            
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/iot", "root", "root");
            //關鍵 設置為手動提交
            conn.setAutoCommit(false);
            statement = conn.createStatement();
            long start = System.currentTimeMillis();
            for(int i = 0; i < 20000; i++) {
                statement.addBatch("insert into user(id, username, password, nickname) values('" + i + "', 'aaaaa', 'bbbbb', 'dccc')"); 
            }
            
            statement.executeBatch();
            conn.commit();
            long end = System.currentTimeMillis();
            System.out.println("end - start = " + (end - start) + " ms");
            
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if(rs != null) 
                    rs.close();

            } catch (SQLException e) {
                e.printStackTrace();
            }    
            
            try {
                if(statement != null)
                    statement.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            try {
                if(conn != null)
                    conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }    
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM