Inserting Single and Multiple Records in MySQL using Java

Java Database Connectivity is an API that helps us to connect a Java program to any SQL Database Instance. This connection gives power to developers to programmatically insert, delete, or update data from the database. JDBC contains in-built methods to run queries and updates on the database.

In this article, we will learn how to insert single and multiple records in MySQL using Java.

Steps to Insert Records in MySQL

Step 1: Set up a MySQL Database

To demonstrate the process of inserting records into a MySQL table, we will create an example database and table inside the MySQL Instance.

Open up your MySQL instance and execute the following lines:

CREATE DATABASE GfgExample;

USE GfgExample;

CREATE TABLE gfgArticles(
articleID INT PRIMARY KEY,
Author VARCHAR(20),
Title TEXT,
Likes INT
);

This SQL script will make a new Database GfgExample and a new table gfgArticles within the database. Once the SQL Instance is set up correctly, we will move on to create a new Java project.

Step 2: Create a project and JDBC setup.

Create a new Java Project in your preferred IDE and add the latest version of the JDBC connector to your project.

Step 3: Writing the Java program step-by step

1. Import necessary Libraries.

First of all, to use JDBC connector inside the java class, we need to import the java.sql files inside the file using the following line.

import java.sql.*;

2. Write the main function.

Create a main function and add a try-catch block inside it. Connecting to a SQL instance using JDBC requires a try-catch block. This is because if the connection fails due to some error, the program will abnormally stop due to runtime errors. To prevent this a try-catch block is needed.

import java.sql.*;
public class app {
public static void main(String[] args) throws Exception {
try{

}
catch(Exception e){
System.out.println(e.toString());
}
}
}

3. Establish Connection

To establish the connection with the database, we will use DriverManager.getConnection(url, username, password) function. This connection will be stored in a variable of ‘Connection’ class. so using this variable we will create statements and execute queries and updates on the database instance.

The URL of the connection will be,

jdbc:mysql://<server-address>:<port-number>/<database-name>

The replace the <server-address>, <port-number> and <database-name> with the actual server address, port number and database name inside the syntax.

  • We are using local instance, that’s why the server address will be localhost.
  • The default port address is mostly 3306.
  • The database name is GfgExample.
  • Therefore the connection URL will be jdbc:mysql://localhost:3306/GfgExample

Then we will make a Statement variable. This will help us to execute queries and updates.

import java.sql.*;
public class app {
public static void main(String[] args) throws Exception {
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/GfgExample", "username", "password");
Statement s = con.createStatement();
System.out.println("Connection established Successfully!");
}
catch(Exception e){
System.out.println(e.toString());
}
}
}

The final program should look something like this. Replace the username and password with the actual username and password.

Now, run the program to see is connection is successfully established or not. If not, please check your entered URL, username and password.

The output should come like this:

Connection established Successfully!

Inserting Single Record in MySQL using Java

To insert a single record inside the table, we will need the function executeUpdate(str). This function will take in the insert query as a string and execute it inside the MySQL database instance.

s.executeUpdate("INSERT INTO TABLE gfgArticles(articleID, Author, Title, Likes) VALUES(1, 'Ishaan Bhela', 'Intro to JDBC', 10");


Here is the complete Java program to insert a single record:

Java
// Java program to insert a single record in MySQL
import java.sql.*;
public class app {
    public static void main(String[] args) throws Exception {
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/GfgExample", "username", "password");
            Statement s = con.createStatement();
            System.out.println("Connection extablished Successfully!");
            s.executeUpdate("INSERT INTO gfgArticles(articleID, Author, Title, Likes) VALUES(1, 'Ishaan Bhela', 'Intro to JDBC', 10);");
            System.out.println("Update executed Successfully!");
        }
        catch(Exception e){
            System.out.println(e.toString());
        }
    }
}


Output:


Lets see if the update is successfully done in the database instance. Execute the following query inside the database instance:

SELECT * FROM gfgArticles;

Database Table:


The record is successfully added into the table using the Java program.

Inserting Multiple Records in MySQL using Java

Inserting multiple records can be done by using:

  • Single executeUpdate statement: This involves adding multiple records into a single String when passing into executeUpdate() function.
  • PreparedStatement and Batch Processing: PreparedStatement is more flexible approach when it comes to dynamic data.

We will see only the second solution and the first one is already done above

1. Creating a Prepared Statement

PreparedStatement is a feature of JDBC which allows programmers to execute queries or updates with parameters. It is an extension of Statement class that provides more functionality and efficiency.

First we need to prepare a query, in the case of this program, its an Insert query.

String query = "INSERT INTO gfgArticles(articleID, Author, Title, Likes) VALUES(?, ?, ?, ?);";

Next we need to create a PreparedStatement variable with the query.

PreparedStatement ps = con.prepareStatement(query);

lets add multiple records in the prepared statement, using the following syntax

ps.setString(int, string)
ps.addBatch();

setString method replaces the question mark with the string. the Integer represents which question mark should be replaces. If the integer is 1, then the first question mark will be replaces by the the given string.

The addBatch method adds the query in execution list but not executes it. It queues up all the queries first.

To execute the prepared Statement, we use:

ps.executeBatch();

Make sure to add your prepared statement to batch queue else it wont be executed.

Illustration:

Java
// Java program to Insert Multiple Records in MySQL
import java.sql.*;
public class app {
    public static void main(String[] args) throws Exception {
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/GfgExample", "username", "password");
            Statement s = con.createStatement();
            System.out.println("Connection extablished Successfully!");
            
            String query = "INSERT INTO gfgArticles(articleID, Author, Title, Likes) VALUES(?, ?, ?, ?);";
            // Adding 1st Record
            PreparedStatement ps = con.prepareStatement(query);
            ps.setString(1, "2");
            ps.setString(2, "Rupi Kaur");
            ps.setString(3, "What is Java?");
            ps.setString(4, "100");
            
            ps.addBatch();
            
            // Adding 2nd Record
            ps.setString(1, "3");
            ps.setString(2, "Ishaan Bhela");
            ps.setString(3, "Intro to OOP");
            ps.setString(4, "150");
            
            ps.addBatch();
            
            ps.setString(1, "4");
            ps.setString(2, "Rupi Kaur");
            ps.setString(3, "Intro to MySQL");
            ps.setString(4, "200");
            
            ps.addBatch();
            
            ps.executeBatch();
            
            System.out.println("Inserted Multiple Records Successfully!");
            
        }
        catch(Exception e){
            System.out.println(e.toString());
        }
    }
}


Output:


Now, execute the following query:

SELECT * FROM gfgArticles;

Database Table:


Here, we can see all the three queries were executed simultaneously and multiple records were added.