JDBC BULK INSERT enables fast insertion of large volumes of data

Source: Internet
Author: User
Tags bulk insert

Today, when you are doing a program that imports Excel data into a database, you are ready to use JDBC BULK Insert because of the large amount of data. Then the Preparedstatement.addbatch () is used, and when the 1w data is added, the insert operation is performed, Preparedstatement.executebatch (). I thought it would be quick, and it took me more than 30 minutes to insert 65,536 data, which was totally unexpected. I asked my colleagues how they handled the bulk data import and found that they were also using JDBC BULK INSERT processing, but unlike me: they used Con.setautocommit (false); Then Preparedstatement.executebatch (), then execute Con.commit (); then try again, what is a miracle? It took half an hour just to import the data, and after adding these two sentences, it took only 15 seconds to complete. So went to check the reason, found on the Internet the following paragraph of explanation:

* When importing data to InnoDB, make sure this MySQL does not has autocommit mode enabled because that

Requires a log flush to disk for every insert. To disable autocommit during your import operation, surround it with

SET autocommit and COMMIT statements:

SET autocommit=0;
... SQL Import Statements ...
COMMIT;

For the first time, it is because there is no setautocommit (false), so for each INSERT statement, a log is written to the disk, so although bulk insert is set, the effect is like a single insert, resulting in very slow insertion.

Some of the code is as follows:

String sql = "INSERT INTO table * * * * * * *"; Con.setautocommit (false= con.preparestatement ( SQL);  for (int i=1; i<65536; i++) {    ps.addbatch ();     // 1w Record insertion once    if (i% 10000 = = 0) {         ps.executebatch ();         Con.commit ();     }} // finally insert less than 1w of data Ps.executebatch (); Con.commit ();

JDBC BULK INSERT enables fast insertion of large volumes of data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.