1. 程式人生 > 資料庫 >向資料庫中批量插入大量資料

向資料庫中批量插入大量資料

1. addBatch(sql)

Class.forName("com.mysql.jdbc.Driver");//指定連線型別
Connection con = DriverManager.getConnection(url, username, password);
PreparedStatement pst = con.prepareStatement("");
for (int i = 0; i < 10; i++) {
    StringBuilder sql = new StringBuilder();
    sql.append("INSERT INTO extenal_studentcj(grade,clazz,zkzh,NAME,scoretext,times) VALUES(");
    sql.append("'").append(i).append("',");
    sql.append("'").append(i).append("',");
    sql.append("'").append(i).append("',");
    sql.append("'").append(i).append("',");
    sql.append("'").append(i).append("',");
    sql.append("'").append(i).append("'");
    sql.append(");");
    pst.addBatch(sql.toString());
}
 
 
pst.executeBatch();
pst.close();
con.close();

2. addBatch()

Class.forName("com.mysql.jdbc.Driver");//指定連線型別
        Connection con = DriverManager.getConnection(url, username, password);
 
        String sql = "INSERT INTO extenal_studentcj(grade,clazz,zkzh,NAME,scoretext,times) VALUES(?,?,?,?,?,?)";
        PreparedStatement pst = con.prepareStatement(sql);
        for (int i = 0; i < 10; i++) {
            int idx = 1;
            pst.setString(idx++, i + "");
            pst.setString(idx++, i + "");
            pst.setString(idx++, i + "");
            pst.setString(idx++, i + "");
            pst.setString(idx++, i + "");
            pst.setLong(idx++, i);
            pst.addBatch();
        }
        pst.executeBatch();
        pst.close();
        con.close();

後來才發現要批量執行的話,JDBC連線URL字串中需要新增一個引數:rewriteBatchedStatements=true

例如:jdbc:mysql://127.0.0.1:8080/xihudb?rewriteBatchedStatements=true

沒有 rewriteBatchedStatements=true 則都是forEach. 開啟後 addBatch(),addBatch(sql)使用的都是一次傳送

3. 拼接SQL語句

拼接SQL

<insert id="insert" parameterType="com.Info">
    insert into pp (str1, str2)
    values
    <foreach collection="ps" item="p" separator=",">
        (#{p.str1,jdbcType=VARCHAR},
        #{p.str2,jdbcType=VARCHAR},
    </foreach>
</insert>

三者之間的相對速度比較:
JDBC BATCH(1)> Mybatis BATCH(2) > 拼接SQL(4)