How to Execute Multiple SQL Commands on a Database Simultaneously in JDBC?
Last Updated :
08 Jun, 2022
Java Database Connectivity also is known as JDBC is an application programming interface in Java that is used to establish connectivity between a Java application and database. JDBC commands can be used to perform SQL operations from the Java application. Demonstrating execution of multiple SQL commands on a database simultaneously using the addBatch() and executeBatch() commands of JDBC.

The addBatch() command is used to queue the SQL statements and executeBatch() command is used to execute the queued SQL statements all at once. In order to use SQL statements in the Java application, ''java.sql'' package needs to be imported in the beginning of the Java application. The Java application is connected to the database using the getConnection() method of DriverManager class. The getConnection() method takes three parameters URLs, username and password.
Goal: Demonstrates two examples of which one uses the Statement Interface and the other uses PreparedStatement Interface. The PreparedStatement performs better than the Statement interface. Statement interface can be used to execute static SQL queries whereas PreparedStatement interface is used to execute dynamic SQL queries multiple times.
Example 1: Using Statement Interface
In this example, the java.sql package classes and interfaces are imported. The Statement interface is used to execute the sql statements. The table is creation sql statement along with record insertion sql statement are added to the batch using the addBatch() command. When all the statements are batched the executeBatch() command is executed which runs all the batched queries simultaneously. The sql statements may throw SQL Exceptions which must be handled in a try catch block to avoid abrupt termination of the program. After the table is created and records are inserted, to view the data in the table the select query is executed. The result obtained by executing the select query is stored in the ResultSet cursor. The cursor is iterated using the next() method and the records are displayed on the screen.
Implementation: Using the standard interface
Java
// Step 1: Create a database
// SQL database imported
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class BatchCommand {
// Main driver method
public static void main(String args[])
{
// Try block to check if exception occurs
try {
// Step 2: Loading driver class
// Using forName()
Class.forName("oracle.jdbc.OracleDriver");
// Step 3: Create connection object
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe",
"username", "password");
Statement s = con.createStatement();
// Step 4: Create a statement / create table
String sql1
= "CREATE TABLE STUDENT(STUDENTID VARCHAR2(10) PRIMARY KEY,NAME VARCHAR2(20),DEPARTMENT VARCHAR2(10))";
// Step 5: Process a query
// Insert records in the table
String sql2
= "INSERT INTO STUDENT VALUES('S101','JEAN','CSE')";
String sql3
= "INSERT INTO STUDENT VALUES('S102','ANA','CSE')";
String sql4
= "INSERT INTO STUDENT VALUES('S103','ROBERT','ECE')";
String sql5
= "INSERT INTO STUDENT VALUES('S104','ALEX','IT')";
String sql6
= "INSERT INTO STUDENT VALUES('S105','DIANA','IT')";
s.addBatch(sql1);
s.addBatch(sql2);
s.addBatch(sql3);
s.addBatch(sql4);
s.addBatch(sql5);
s.addBatch(sql6);
// Step 6: Process the results
// execute the sql statements
s.executeBatch();
ResultSet rs
= s.executeQuery("Select * from Student");
// Print commands
System.out.println(
"StudentID\tName\t\tDepartment");
System.out.println(
"-------------------------------------------------------");
// Condition to check pointer pointing
while (rs.next()) {
System.out.println(rs.getString(1) + "\t\t"
+ rs.getString(2)
+ "\t\t"
+ rs.getString(3));
}
// Step 7: Close the connection
con.commit();
con.close();
}
// Catch block to handle exceptions
catch (Exception e) {
// Print line number if exception occurred
System.out.println(e);
}
}
}
SQL commands over database using addBatch() method with the involvement of executeBatch()
Java
// Step 1: Importing database
// SQL database imported
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class BatchCommand {
// Main driver method
public static void main(String args[])
{
// Try block to handle if exception occurs
try {
// Step 2: loading driver class
Class.forName("oracle.jdbc.OracleDriver");
// Step 3: create connection object
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe",
"username", "password");
Statement s = con.createStatement();
// Step 4: Create a statement
// Create table
String sql1
= "CREATE TABLE STUDENT(STUDENTID VARCHAR2(10) PRIMARY KEY,NAME VARCHAR2(20),DEPARTMENT VARCHAR2(10))";
// Step 5: Execute a query
// Insert records in the table
String sql2
= "INSERT INTO STUDENT VALUES('S101','JEAN','CSE')";
String sql3
= "INSERT INTO STUDENT VALUES('S102','ANA','CSE')";
String sql4
= "INSERT INTO STUDENT VALUES('S103','ROBERT','ECE')";
String sql5
= "INSERT INTO STUDENT VALUES('S104','ALEX','IT')";
String sql6
= "INSERT INTO STUDENT VALUES('S105','DIANA','IT')";
s.addBatch(sql1);
s.addBatch(sql2);
s.addBatch(sql3);
s.addBatch(sql4);
s.addBatch(sql5);
s.addBatch(sql6);
// Step 6: Process the statements
// Create an int[] to hold returned values
s.executeBatch();
ResultSet rs
= s.executeQuery("Select * from Student");
// Print statements
System.out.println(
"StudentID\tName\t\tDepartment");
System.out.println(
"-------------------------------------------------------");
// Condition check for pointer pointing which
// record
while (rs.next()) {
System.out.println(rs.getString(1) + "\t\t"
+ rs.getString(2)
+ "\t\t"
+ rs.getString(3));
}
// Step 7: Close the connection
con.commit();
con.close();
}
// Catch block to handle exception
catch (Exception e) {
// Print line number where exception occurred
System.out.println(e);
}
}
}
Output

Example 2: In this example, the java.sql package classes and interfaces are imported. The PreparedStatement interface is used to execute the SQL statements. The table is the creation SQL statement along with record insertion SQL statement are added to the batch using the addBatch() command. When all the statements are batched the executeBatch() command is executed which runs all the batched queries simultaneously. The sql statements may throw SQL Exceptions which must be handled in a try-catch block to avoid abrupt termination of the program. After the table is created and records are inserted, to view the data in the table the select query is executed. The result obtained by executing the select query is stored in the ResultSet cursor. The cursor is iterated using the next() method and the records are displayed on the screen. Unlike the previous example, it takes dynamic input from the user. Hence, using the PreparedStatement has performance benefits.
Code Implementation
Java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.*;
public class AddBatchCommand {
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
try {
// loading driver class
Class.forName("oracle.jdbc.OracleDriver");
// create connection object
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe",
"username", "password");
// create the table
String sql1
= "CREATE TABLE STUDENTS(STUDENTID VARCHAR2(10) PRIMARY KEY,NAME VARCHAR2(20),DEPARTMENT VARCHAR2(10))";
PreparedStatement ps
= con.prepareStatement(sql1);
ps.execute(sql1);
// inserting records
String sql
= "Insert into Students values(?,?,?)";
PreparedStatement ps1
= con.prepareStatement(sql);
for (int i = 0; i < 3; i++) {
System.out.println("Enter Student ID");
String id = scan.nextLine();
System.out.println("Enter Student Name");
String name = scan.nextLine();
System.out.println("Enter the Department");
String dept = scan.nextLine();
ps1.setString(1, id);
ps1.setString(2, name);
ps1.setString(3, dept);
// adding to batch
ps1.addBatch();
}
// executing the batch
ps1.executeBatch();
// viewing the table
ResultSet rs
= ps.executeQuery("Select * from Students");
System.out.println(
"StudentID\tName\t\tDepartment");
System.out.println(
"-------------------------------------------------------");
while (rs.next()) {
System.out.println(rs.getString(1) + "\t\t"
+ rs.getString(2)
+ "\t\t"
+ rs.getString(3));
}
con.commit();
con.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
Output: Illustrating multiple SQL commands on a database simultaneously:

Similar Reads
Oracle DataBase - Grant Privileges to a User in SQL Command Line
Oracle Database is a robust and widely utilized relational database management system (RDBMS) recognized for its scalability, advanced features and performance optimization. Its architecture supports complex queries and large datasets also making it a popular choice for organizations of all sizes. I
4 min read
How to Alter Multiple Columns at Once in SQL Server?
In SQL, sometimes we need to write a single query to update the values of all columns in a table. We will use the UPDATE keyword to achieve this. For this, we use a specific kind of query shown in the below demonstration. For this article, we will be using the Microsoft SQL Server as our database an
3 min read
How to Open a Database in SQL Server?
Opening a database in SQL Server is a fundamental task for database administrators and developers. It involves establishing a connection to the server instance and selecting a database to work with. In this article, we will explore two methods to open a database in SQL Server such as using SQL Serve
3 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 Show a List of Databases in PL/SQL?
Managing databases is a fundamental aspect of database administration and development. In Oracle Database, schemas represent logical containers for database objects like tables, views, procedures, and functions. PL/SQL is the procedural extension of and used in Oracle Database and provides powerful
5 min read
How to Execute Mongo Commands Through Shell Scripts?
Database management is a difficult field and MongoDB is a useful NoSQL database in this area. Automation of tasks through shell scripts is the way of effectively utilizing the abilities of a shell program. In this article, we will learn about How to execute MongoMongo commands through shell scripts
3 min read
Selecting Multiple Columns Based On Condition in SQL
SQL (Structured Query Language) is used to manage and query databases. One common requirement when querying data is selecting multiple columns based on specific conditions. Understanding how to use SQL for this purpose can enhance your ability to retrieve relevant data efficiently. In this article,
4 min read
How to Show all Columns in the SQLite Database using Python ?
In this article, we will discuss how we can show all columns of a table in the SQLite database from Python using the sqlite3 module. Approach:Connect to a database using the connect() method.Create a cursor object and use that cursor object created to execute queries in order to create a table and
3 min read
How to Protect Against SQL Injection Attacks?
SQL Injection, often known as SQLI, is a typical attack vector that employs malicious SQL code to manipulate Backend databases in order to obtain information that was not intended to be shown. This information might contain sensitive corporate data, user lists, or confidential consumer information.
4 min read
How To Update Multiple Columns in MySQL?
To update multiple columns in MySQL we can use the SET clause in the UPDATE statement. SET clause allows users to update values of multiple columns at a time. In this article, we will learn how to update multiple columns in MySQL using UPDATE and SET commands. We will cover the syntax and examples,
3 min read