通過最簡單的方式將批量數據插入數據庫中,千萬條記錄導入時間用了100s,貼出來代碼供大家參考學習。
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Date; /** * @Author BlueFire * @Date 2020/4/17 -22:13 */ public class InsertTest { public static void main(String[] args) throws ClassNotFoundException, SQLException { final String url = "jdbc:mysql://127.0.0.1:3306/mooding?autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai"; 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_users (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 <= 1000; i++) { suffix = new StringBuffer(); // 第j次提交步長 for (int j = 1; j <= 10000; j++) { // 構建SQL后綴 suffix.append("('" + System.currentTimeMillis()* j + "','" + 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("插入完成"); } }
志在分享一些學經驗和技巧,如有志同道合的朋友可以添加個人微信,絕不推廣任何廣告,純屬個人交易,廣告請勿擾