一、思路
往MySQL中插入1000000條數(shù)據(jù)只花了6秒鐘!
關(guān)鍵點:
1.使用PreparedStatement對象
2.rewriteBatchedStatements=true 開啟批量插入,插入只執(zhí)行一次,所有插入比較快。
二、 代碼
package test0823.demo1; import java.sql.*; /** * @author : Bei-Zhen * @date : 2020-08-24 0:43 */ public class JDBC2 { //static int count = 0; public static void main(String[] args) { long start = System.currentTimeMillis(); conn(); long end = System.currentTimeMillis(); System.out.println("耗時:" + (end - start)/1000 + "秒"); } public static void conn(){ //1.導(dǎo)入驅(qū)動jar包 //2.注冊驅(qū)動(mysql5之后的驅(qū)動jar包可以省略注冊驅(qū)動的步驟) //Class.forName("com.mysql.jdbc.Driver"); //3.獲取數(shù)據(jù)庫連接對象 Connection conn = null; PreparedStatement pstmt = null; { try { //"rewriteBatchedStatements=true",一次插入多條數(shù)據(jù),只插入一次 conn = DriverManager.getConnection("jdbc:mysql:///test?" + "rewriteBatchedStatements=true","root","root"); //4.定義sql語句 String sql = "insert into user values(default,?,?)"; //5.獲取執(zhí)行sql的對象PreparedStatement pstmt = conn.prepareStatement(sql); //6.不斷產(chǎn)生sql for (int i = 0; i 1000000; i++) { pstmt.setString(1,(int)(Math.random()*1000000)+""); pstmt.setString(2,(int)(Math.random()*1000000)+""); pstmt.addBatch(); } //7.往數(shù)據(jù)庫插入一次數(shù)據(jù) pstmt.executeBatch(); System.out.println("添加1000000條信息成功!"); } catch (SQLException e) { e.printStackTrace(); } finally { //8.釋放資源 //避免空指針異常 if(pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } } }
三、運行結(jié)果
添加1000000條信息成功!
耗時:6秒
到此這篇關(guān)于教你如何6秒鐘往MySQL插入100萬條數(shù)據(jù)的實現(xiàn)的文章就介紹到這了,更多相關(guān)MySQL插入100萬條數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
標簽:阜新 鎮(zhèn)江 北京 貴州 鷹潭 日照 合肥 臺灣
巨人網(wǎng)絡(luò)通訊聲明:本文標題《教你如何6秒鐘往MySQL插入100萬條數(shù)據(jù)的實現(xiàn)》,本文關(guān)鍵詞 教你,如何,6秒鐘,往,MySQL,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。