1. 程式人生 > 資料庫 >88秒插入1000萬條資料到MySQL資料庫表的操作方法

88秒插入1000萬條資料到MySQL資料庫表的操作方法

我用到的資料庫為,mysql資料庫5.7版本的

首先自己準備好資料庫表

其實我在插入1000萬條資料的時候遇到了一些問題,現在先來解決他們,一開始我插入100萬條資料時候報錯,控制檯的資訊如下:

com.mysql.jdbc.PacketTooBigException: Packet for query is too large (4232009 > 4194304). You can change this value on the server by setting the max_allowed_packet' variable.

出現上面的錯誤是因為資料庫表的 max_allowed_packet 這個配置沒配置足夠大,因為預設的為4M的,後來我調為100M就沒報錯了

set global max_allowed_packet = 100*1024*1024* 

記住,設定好後重新登入資料庫才能看的設定後的值

show VARIABLES like '%max_allowed_packet%'

程式碼如下:

package insert;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;
import com.mysql.jdbc.PreparedStatement;
public class InsertTest {
   public static void main(String[] args) throws ClassNotFoundException,SQLException {
     final String url = "jdbc:mysql://127.0.0.1/teacher" ; 
     final String name = "com.mysql.jdbc.Driver" ; 
     final String user = "root" ; 
     final String password = "123456" ; 
     Connection conn = null ; 
     Class.forName(name); //指定連線型別 
     conn = DriverManager.getConnection(url,user,password); //獲取連線 
     if (conn!= null ) {
       System.out.println( "獲取連線成功" );
       insert(conn);
     } else {
       System.out.println( "獲取連線失敗" );
     }
   }
   public static void insert(Connection conn) {
     // 開始時間
     Long begin = new Date().getTime();
     // sql字首
     String prefix = "INSERT INTO t_teacher (id,t_name,t_password,sex,description,pic_url,school_name,regist_date,remark) VALUES " ;
     try {
       // 儲存sql字尾
       StringBuffer suffix = new StringBuffer();
       // 設定事務為非自動提交
       conn.setAutoCommit( false );
       // 比起st,pst會更好些
       PreparedStatement pst = (PreparedStatement) conn.prepareStatement( "" ); //準備執行語句
       // 外層迴圈,總提交事務次數
       for ( int i = 1 ; i <= 100 ; i++) {
         suffix = new StringBuffer();
         // 第j次提交步長
         for ( int j = 1 ; j <= 100000 ; j++) {
           // 構建SQL字尾
           suffix.append( "('" + uutil.UUIDUtil.getUUID()+ "','" +i*j+ "','123456'" + ",'男'" + ",'教師'" + ",'www.bbk.com'" + ",'XX大學'" + ",'" + "2016-08-12 14:43:26" + "','備註'" + ")," );
         }
         // 構建完整SQL
         String sql = prefix + suffix.substring( 0,suffix.length() - 1 );
         // 新增執行SQL
         pst.addBatch(sql);
         // 執行操作
         pst.executeBatch();
         // 提交事務
         conn.commit();
         // 清空上一次新增的資料
         suffix = new StringBuffer();
       }
       // 頭等連線
       pst.close();
       conn.close();
     } catch (SQLException e) {
       e.printStackTrace();
     }
     // 結束時間
     Long end = new Date().getTime();
     // 耗時
     System.out.println( "1000萬條資料插入花費時間 : " + (end - begin) / 1000 + " s" );
     System.out.println( "插入完成" );
   }
}

總結

以上所述是小編給大家介紹的88秒插入1000萬條資料到MySQL資料庫表的操作方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對我們網站的支援!