教你如何6秒鐘往MySQL插入100萬條數(shù)據(jù)的實(shí)現(xiàn)
一、思路
往MySQL中插入1000000條數(shù)據(jù)只花了6秒鐘!
關(guān)鍵點(diǎ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(); } } } } } }
三、運(yùn)行結(jié)果
添加1000000條信息成功!
耗時:6秒
到此這篇關(guān)于教你如何6秒鐘往MySQL插入100萬條數(shù)據(jù)的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)MySQL插入100萬條數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
mysql中sum float類型使用小數(shù)點(diǎn)的方法
使用sum示和時如果是float類型的數(shù)據(jù)就會出現(xiàn)小數(shù)點(diǎn)了,那么要如何解決這個問題,下面介紹二種方法2013-11-11MySQL索引類型Normal、Unique和Full Text的講解
今天小編就為大家分享一篇關(guān)于MySQL索引類型Normal、Unique和Full Text的講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03淺析centos 7 mysql-8.0.19-1.el7.x86_64.rpm-bundle.tar
這篇文章主要介紹了centos 7 mysql-8.0.19-1.el7.x86_64.rpm-bundle.tar的相關(guān)知識,需要的朋友可以參考下2020-01-01MySQL內(nèi)連接和外連接及七種SQL?JOINS的實(shí)現(xiàn)
這篇文章主要介紹了Mysql內(nèi)連接和外連接的區(qū)別以及七種SQL?Joins的實(shí)現(xiàn),相信看完這篇文章你對SQL內(nèi)外連接的多表查詢就足夠理解了,需要的朋友可以參考下2023-03-03MySQL全文索引、聯(lián)合索引、like查詢、json查詢速度哪個快
這篇文章主要介紹了MySQL全文索引、聯(lián)合索引、like查詢、json查詢速度大比拼,通過實(shí)例代碼截圖的形式給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02集群運(yùn)維自動化工具ansible使用playbook安裝mysql
本文主要介紹了如何使用playbook安裝mysql,需要的朋友可以參考下2014-07-07