5 語句批處理(Batch)

import java.sql.*;

/**
 * 批處理Batch
 * @author Administrator
 *
 */
public class TestBatch {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        
        try {
            //1:加載驅動類
            Class.forName("com.mysql.jdbc.Driver");
            
            //2:建立連接(連接對象內部其實包含Socket對象,是一個遠程的連接,比較耗時,這是Connection對象管理的一個要點)
            //真正的開發中,都會使用連接池來管理對象
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/test","root","123456");
            
            //將事務設為手動提交
            conn.setAutoCommit(false);
            long start = System.currentTimeMillis();
            stmt = conn.createStatement();
            
            for(int i=0; i<20000;i++){
                stmt.addBatch("insert into user (name,age) values ('TFBoy吃屎"+i+"',12)");
            }
            stmt.executeBatch();
            
            //提交事務
            conn.commit();
            
            long end = System.currentTimeMillis();
            System.out.println("插入兩萬行TFBoy吃屎,耗時(毫秒):" + (end-start));
            
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            
            //關閉順序遵循:ResultSet-->Statement->Connection
            if(rs != null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            
            if(stmt != null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容