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

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)

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值