Inserting Single and Multiple Records in MySQL using Java
Last Updated :
10 Jun, 2024
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.
Similar Reads
Inserting Records in Batch Using JDBC
It is carried out using the functions namely addBatch() and executeBatch() methods. For that lets us do have a prior understanding of JDBC drivers. So, in order to connect to your database in Java, you need a JDBC driver. Every database (MySQL, Oracle, etc.) comes with its own JDBC driver, usually b
2 min read
How to UPDATE Multiple ROWs in a Single Query in MySQL?
In the world of database management efficiency, perfection, accuracy & precision are considered to play a vital role. When it comes to MySQL stands for âStructured Query Languageâ, MySQL is the most common standardized language used for database management currently. A database is a structured c
5 min read
PostgreSQL - Insert Multiple Values in Various Rows
PostgreSQL, one of the most popular relational database management systems (RDBMS), is widely used for storing structured data in a tabular format, much like MySQL. In relational databases, data is stored in tables where each row represents a record and each column represents an attribute. One of th
3 min read
How to Insert Multiple Rows in SQLite?
In the area of database management, efficiency is key. When working with SQLite, a lightweight database engine, inserting multiple rows efficiently can significantly boost performance and speed our workflow. In this article, We will understand how to insert multiple rows in SQLite through various me
3 min read
MySQL Insert Multiple Rows
MySQL is an open-source Relational Database Management System that stores data in rows and columns. MySQL is designed to be platform-independent, which means it can run on various operating systems, including Windows, Linux, macOS, and more. MySQL is scalable and can handle databases of varying size
5 min read
How to Insert Multiple Rows at Once in PL/SQL?
As the volume and complexity of data continue to grow in modern systems, efficient data management techniques become important. One fundamental operation in database management is the insertion of multiple rows at once. In this article, we understand the techniques and methods available in PL/SQL fo
5 min read
How to Insert Multiple Rows to a Table in PostgreSQL?
Inserting multiple rows into a table in PostgreSQL is a common and efficient operation, especially when handling large datasets. By executing a single SQL query, multiple rows can be added simultaneously, reducing overhead and enhancing performance. This method is particularly valuable in scenarios
5 min read
Spring Data JPA - Find Records From MySQL
Spring Data JPA simplifies database interactions in Spring Boot applications by providing a seamless way to work with relational databases like MySQL. It eliminates boilerplate code and allows developers to perform CRUD operations efficiently using JPA repositories. With Spring Boot and Spring Data
3 min read
Spring Data JPA - Insert Data in MySQL Table
Spring Data JPA makes it easy to work with databases in Spring Boot by reducing the need for boilerplate code. It provides built-in methods to perform operations like inserting, updating, and deleting records in a MySQL table. In this article, we will see how to insert data into a MySQL database usi
3 min read
SQL Query to Insert Multiple Rows
In SQL, the INSERT statement is used to add new records to a database table. When you need to insert multiple rows in a single query, the INSERT statement becomes efficient. In this article, We will learn different methods such as using basic INSERT statements, utilizing INSERT INTO ... SELECT for b
4 min read