如何利用jdbc快速插入百万条数据

当须要向数据库插入百万条数据时,利用hibernate,mybatis等持久层框架时耗时较久,此时使用jdbc插入效率会更高。此种场景特别适用于读取文件导入到数据库。可以利用批处理来加快jdbc的插入效率。

String sql = "insert into person(id,name) values(?,?)";
Connection c = ConnectionUtil.getConn();
PreparedStatement ps = c.prepareStatement(sql);
for (int i = 0; i < 1000; i++) {
    ps.setInt(1, (i + 1));
    ps.setString(2, "a" + i);
    ps.addBatch();
}
ps.executeBatch();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

同时可以增长单条sql语句的长度,如:

String sql = "insert into person(id,name) values(?,?),(?,?)";
Connection c = ConnectionUtil.getConn();
PreparedStatement ps = c.prepareStatement(sql);
ps.setInt(1, 1);
ps.setString(2, "a" + 1);
ps.setInt(3, 2);
ps.setString(4, "a" + 2);
ps.addBatch();
ps.executeBatch();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

快速插入百万对象到数据库,可以利用jdbc工具类,方便的插入数据。

JdbcMapper j = new JdbcMapper();
List<Msg> ms = new ArrayList<>();
Msg m = new Msg();
for (int i = 0; i < count; i++) {
    m.setMsgName("aa" + i);
    m.setCreateTime(new Date());
    m.setRemark("inserts");
    ms.add(m);
}
j.insertMillionObjects(ms, 10000, 500);

猜你喜欢

转载自blog.csdn.net/wuqianjing/article/details/80166359