mysql数据库批量快速插入_MySQL

WBOY
풀어 주다: 2016-06-01 12:58:49
원래의
1034명이 탐색했습니다.

最近在处理一批数据,需要从库中表里的字段进行处理然后导出到一个新表中。不过这个表的数据量有近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(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); }finally { if(conn!=null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
로그인 후 복사

2k行插入耗时大概是260ms。
2w行数据插入大概是1.4s。
其实结果很明显的。

因为在使用batch时数据量达到一定的值后数据库会自动提交。而不是你执行executeBatch时再执行。所以我们需要修改自动提交变成手动提交。
这里还有一个问题是:当你实在执行事务时,一旦出错的时候,自动提交会帮你rollback,手动提交时就应该自己进行回退。
所以在catch里需要添加 rollback 。

好了,综上我们可以使用自动提交的batch进行大量数据的插入。

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!