码迷,mamicode.com
首页 > 数据库 > 详细

mysql数据库批量高速插入

时间:2017-06-26 20:04:23      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:except   nal   print   简单   false   时间   not   java   user   

近期在处理一批数据,须要从库中表里的字段进行处理然后导出到一个新表中。只是这个表的数据量有近500w条。

这数据量出现的的问题是须要处理的时间好长。
首先想到,一句一句的插入,大数据量处理时间好长,忽略。


其次想到,多线程插入,想到数据库连接是须要同步的所以感觉用处不大。
最后想到,使用 PreparedStatement 预编译sql 进行批量插入 batch 处理。


好吧。如今就进行批处理插入測试。
1、使用简单的 batch

public static void main(String[] args) {
        Connection conn = getConn(lsqlurl, luser, lpassword);
        long startTime = System.currentTimeMillis();
        try {
            PreparedStatement pst = conn.prepareStatement("insert into testmy (id,name,age) values (?

,?,?

)"); for (int i = 0; i < 2000; i++) { pst.setInt(1, 3); pst.setString(2, "xx"); pst.setInt(3, 10); pst.addBatch(); } pst.executeBatch(); long endTime = System.currentTimeMillis(); System.out.println((endTime - startTime)/1000+"s"); System.out.println("test sql batch--->2000....."); } catch (SQLException e) { e.printStackTrace(); }finally { if(conn!=null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }

你会发现时间会是30s 左右。


2k行的数据插入就30秒 。
2w行数据插入时间为940秒(约16min)。

2、改动自己主动提交的 batch

public static void main(String[] args) {
        Connection conn = getConn(lsqlurl, luser, lpassword);
        long startTime = System.nanoTime();
        try {
            conn.setAutoCommit(false);
            PreparedStatement pst = conn.prepareStatement("insert into test (id,name,age) values (?,?,?

)"); for (int i = 0; i < 2000; i++) { pst.setInt(1, 3); pst.setString(2, "xx"); pst.setInt(3, 10); pst.addBatch(); } pst.executeBatch(); conn.commit(); long endTime = System.nanoTime(); System.out.println((endTime - startTime)/1000000+"ms"); System.out.println("test sql batch--->2000....."); } catch (SQLException e) { try { conn.rollback();

mysql数据库批量高速插入

标签:except   nal   print   简单   false   时间   not   java   user   

原文地址:http://www.cnblogs.com/tlnshuju/p/7081954.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!