DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Why Database Migrations Take Months and How to Speed Them Up
  • Unmasking Entity-Based Data Masking: Best Practices 2025
  • How Trustworthy Is Big Data?
  • Fixing Common Oracle Database Problems

Trending

  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer
  • Accelerating AI Inference With TensorRT
  • Mastering Advanced Aggregations in Spark SQL
  • Unlocking AI Coding Assistants: Generate Unit Tests
  1. DZone
  2. Data Engineering
  3. Databases
  4. Performant Batch Inserts Using JDBC

Performant Batch Inserts Using JDBC

This simple change may significantly improve the performance of your bulk inserts into a database via JDBC.

By 
Duncan Brown user avatar
Duncan Brown
·
Feb. 25, 19 · Tutorial
Likes (10)
Comment
Save
Tweet
Share
34.1K Views

Join the DZone community and get the full member experience.

Join For Free

The Problem

If you've ever tried to insert data via a JDBC connection — say to a MySQL database — in bulk, then you may have had to sit through several minutes or even hours for hundreds of thousands — or even millions —of records to finish being added to the database. Even without the overhead of transactions, this wait time is comparable.

So what can we do to improve the performance of these bulk inserts?  Interestingly, there is something small that can be adjusted that can have a very large impact.

Let's consider the following example:

  Connection connection = null;

  // connect to the database here and set the "connection" variable

  try {
    String query = "INSERT INTO table1 (field1, field2) VALUES (?, ?)";

    PreparedStatement preparedStatement = connection.prepareStatement(query);

    for (int i = 0; i < 1000000) {
      preparedStatement.setString(1, "value" + i);
      preparedStatement.setInt(2, i);

      preparedStatement.addBatch();
    }

    preparedStatement.executeBatch();
  } catch (SQLException e1) {
    // handle the exception
  }


The above code simply creates a batch insert using a PreparedStatement from the java.sql library.

Nothing surprising there.

However, let's take a look at how the connection to the database is established:

try {
  String connectionString = "jdbc:mysql://localhost:3306/my_db"; // be sure to add any other parameters needed to ensure an authorized connection

  Class.forName("com.mysql.cj.jdbc.Driver"); // ...or your favorite JDBC driver

  this.connection = DriverManager.getConnection(connectionString);
} catch (ClassNotFoundException | SQLException e) {
  // deal with the exceptioun
}


With the above code segments, we have a fairly typical interaction with a MySQL database via a JDBC driver.

However, most who run this code will notice how painfully slow the overall process is.

A Possible Solution

So what can be done?

One simple setting in the connection string may make a world of difference.

If we add the following to our connection string rewriteBatchedStatements=true, like the following:

  String connectionString = "jdbc:mysql://localhost:3306/my_db?rewriteBatchedStatements=true"


(...of course, being sure to augment the connection string with any other parameters, such as those to ensure an authenticated connection...)

And then, re-run the above code segments; you should notice a substantial increase in performance!

How Does It Work?

Quite simply, the connection string setting we added tells the database to take any series of individual INSERT statements and convert them to a single multi-value INSERT statement, e.g.:

INSERT INTO table1 (field1, field2) VALUES ("string1", 1);
INSERT INTO table1 (field1, field2) VALUES ("string2", 2);
INSERT INTO table1 (field1, field2) VALUES ("string3", 3);
INSERT INTO table1 (field1, field2) VALUES ("string4", 4);


becomes...

INSERT INTO table1 (field1, field2) VALUES  ("string1", 1), 
("string2", 2), 
                                            ("string3", 3), 
                                            ("string4", 4);


Give it a shot the next time you run into this situation! Let me know how it goes in the comments below.

Database

Opinions expressed by DZone contributors are their own.

Related

  • Why Database Migrations Take Months and How to Speed Them Up
  • Unmasking Entity-Based Data Masking: Best Practices 2025
  • How Trustworthy Is Big Data?
  • Fixing Common Oracle Database Problems

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!