欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

教你如何6秒鐘往MySQL插入100萬條數(shù)據(jù)的實(shí)現(xiàn)

 更新時間:2020年08月28日 11:24:09   作者:Bei-Zhen  
這篇文章主要介紹了教你如何6秒鐘往MySQL插入100萬條數(shù)據(jù)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

一、思路

往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)文章

最新評論