Insert Multiple Records Into Database Using Prepared Statement In Java

LEVEL: Beginner

Whats in this post?

  1. Code
  2. Output
  3. Background and Explanation of the code


To copy code: Click  View Source “View Source” on the right of this code snippet.

Background and Explanation of the code

This program connects to MySQL database using Type-4 JDBC driver. To get and configure database driver, follow the instructions provided on following post:

In this program we are using PreparedStatement to insert multiple records into database table. The main feature of a PreparedStatement object is that, unlike a Statement object, it is given a SQL statement when it is created. The advantage to this is that in most cases, this SQL statement is sent to the DBMS right away, where it is compiled. As a result, the PreparedStatement object contains not just a SQL statement, but a SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PrepareStatement SQL statement without having to compile it first. In case of multiple records this feature provides better performance.

To compile the program: javac

To run the program: java InsertMultipleRecords

After running the program, check the database table, it will have two newly inserted records.