一對一的表怎麼插入資料_怎麼快速插入 1000 W條資料,用時最短
阿新 • • 發佈:2020-12-09
技術標籤:一對一的表怎麼插入資料
package com.khd.project.order; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Date; public class InsertTest { public static void main(String[] args) throws ClassNotFoundException, SQLException { final String url = "jdbc:mysql://localhost:3306/ry?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8"; final String name = "com.mysql.jdbc.Driver"; final String user = "root"; final String password = "mango123"; 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 (name, age) 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("('" + "cxx" + j + "'," + j + "),"); } // 構建完整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("插入完成"); } }