共計 2405 個字符,預計需要花費 7 分鐘才能閱讀完成。
這篇文章將為大家詳細講解有關如何實現 88 秒插入 1000 萬條數據到 MySQL 數據庫表,丸趣 TV 小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
我用到的數據庫為,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 數據庫表”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
正文完