向数据库中批量插入大量数据

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)

上一篇:vue js弹窗功能实现


下一篇:C3P0连接演示