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