Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Browser testing is essential if you have a website or web applications that users interact with. Manual testing can be very helpful to an extent, but given the multiple browsers available, not to mention versions and operating system, testing everything manually becomes time-consuming and repetitive.

To help automate this process, Selenium is a popular choice for developers, as an open-source tool with a large and active community. What's more, we can further scale our automation testing by running on theLambdaTest cloud-based testing platform.

Read more through our step-by-step tutorial on how to set up Selenium tests with Java and run them on LambdaTest:

>> Automated Browser Testing With Selenium

Partner – Orkes – NPI EA (cat=Java)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

1. Overview

When working with a database using Java and JDBC, there are scenarios where we need to execute multiple SQL statements as a single operation. It can help us improve the application performance, ensure atomicity, or manage complex workflows more effectively.

In this tutorial, we’ll explore various ways to execute multiple SQL statements in JDBC.

We’ll cover examples using Statement object, Batch processing, and Stored procedures to demonstrate how to execute multiple SQL queries efficiently. For this tutorial, we’ll use MySQL as the database.

2. Setting up JDBC and Database

Before diving into the code, let’s first ensure that our project is set up correctly and the database is configured.

2.1. Maven Dependencies

To get started, we’ll add the following dependency in our pom.xml file to include the MySQL JDBC driver:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId 
    <version>8.0.33</version>
</dependency>

2.2. Database Configuration

We’ll create a MySQL database named user_db and a table named users for this example and execute multiple insert queries for it:

CREATE DATABASE user_db;
USE user_db;

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE
);

With this database setup, we’re ready to run multiple SQL statements using JDBC.

3. Executing Multiple Queries as One in Java

Before executing multiple queries, we must ensure the database connection is configured correctly to allow multiple statements. Specifically, for MySQL, the connection URL should include the property allowMultiQueries=true to enable this functionality. First, we’ll set up the connection:

public Connection getConnection() throws SQLException {
    String url = "jdbc:mysql://localhost:3306/user_db?allowMultiQueries=true";
    String username = "username";
    String password = "password";

    return DriverManager.getConnection(url, username, password);
}

This configuration will ensure that MySQL accepts multiple SQL statements separated by semicolons in a single execution. By default, MySQL doesn’t allow multi-statement execution in a single execute() call unless the connection string includes the allowMultiQueries=true property.

There are three primary methods for executing multiple SQL statements in JDBC.

3.1. Using Statement Object

The Statement object allows us to execute multiple SQL queries by combining them into a single string separated by semicolons. Here’s an example where we insert multiple records to the newly created users table:

public boolean executeMultipleStatements() throws SQLException {
    String sql = "INSERT INTO users (name, email) VALUES ('Alice', '[email protected]');" +
      "INSERT INTO users (name, email) VALUES ('Bob', '[email protected]');";

    try (Statement statement = connection.createStatement()) {
        statement.execute(sql);
        return true;
    }
}

We’ll also add a test to verify the functionality of executing multiple SQL statements using a single Statement object. The SQL logic used ensures correct insertion into the database:

@Test
public void givenMultipleStatements_whenExecuting_thenRecordsAreInserted() throws SQLException {
    boolean result = executeMultipleStatements(connection);
    assertTrue(result, "The statements should execute successfully.");

    try (Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(
          "SELECT COUNT(*) AS count FROM users WHERE name IN ('Alice', 'Bob')");) {
        resultSet.next();
        int count = resultSet.getInt("count");
        assertEquals(2, count, "Two records should have been inserted.");
    }
}

Please note, that executing multiple SQL statements in a single execute() call varies across database systems. Some databases support this feature natively, while others either require additional configurations or do not support it at all.

We have seen the example with the MySQL database above, which supports multi-statement execution, but it requires enabling the connection string property allowMultiQueries=true in the connection URL. PostgreSQL and SQL Server databases allow multiple SQL statements to be executed in a single execute() call without extra configuration.

Others, like Oracle and H2 databases, don’t support executing multiple statements in a single execute() call. Each SQL statement must be executed individually using separate calls to execute() or through batch processing using addBatch().

3.2. Using Batch Processing

Batch processing is a more efficient way to execute multiple queries when they don’t need to be executed as a single atomic unit.

public int[] executeBatchProcessing() throws SQLException {
    try (Statement statement = connection.createStatement()) {
        connection.setAutoCommit(false);

        statement.addBatch("INSERT INTO users (name, email) VALUES ('Charlie', '[email protected]')");
        statement.addBatch("INSERT INTO users (name, email) VALUES ('Diana', '[email protected]')");

        int[] updateCounts = statement.executeBatch();
        connection.commit();

        return updateCounts;
    }
}

To verify this works as expected, we’ll add a test case:

@Test
public void givenBatchProcessing_whenExecuting_thenRecordsAreInserted() throws SQLException {
    int[] updateCounts = executeBatchProcessing(connection);
    assertEquals(2, updateCounts.length, "Batch processing should execute two statements.");

    try (Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(
          "SELECT COUNT(*) AS count FROM users WHERE name IN ('Charlie', 'Diana')");) {
        resultSet.next();
        int count = resultSet.getInt("count");
        assertEquals(2, count, "Two records should have been inserted via batch.");
    }
}

This test ensures that batch processing executes all the added statements correctly and verifies the number of rows inserted.

3.3. Handling Stored Procedures

Stored procedures precompile SQL code and store it in the database, allowing them to execute multiple statements in one call. To demonstrate it, we’ll create a stored procedure:

DELIMITER //

CREATE PROCEDURE InsertMultipleUsers()
BEGIN
    INSERT INTO users (name, email) VALUES ('Eve', '[email protected]');
    INSERT INTO users (name, email) VALUES ('Frank', '[email protected]');
END //

DELIMITER ;

To run this stored procedure, we’ll add the following code:

public boolean callStoredProcedure() throws SQLException {
    try (CallableStatement callableStatement = connection.prepareCall("{CALL InsertMultipleUsers()}")) {
        callableStatement.execute();
        return true;
    }
}

Next, we’ll add a test that validates that the stored procedure inserts the records into the database as expected:

@Test
public void givenStoredProcedure_whenCalling_thenRecordsAreInserted() throws SQLException {
    boolean result = callStoredProcedure(connection);
    assertTrue(result, "The stored procedure should execute successfully.");

    try (Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(
          "SELECT COUNT(*) AS count FROM users WHERE name IN ('Eve', 'Frank')");) {
        resultSet.next();
        int count = resultSet.getInt("count");
        assertEquals(2, count, "Stored procedure should have inserted two records.");
    }
}

This approach ensures that multiple insert operations are executed efficiently within a single stored procedure call. Also, it enhances performance by reducing the overhead of multiple individual queries.

3.4. Executing Multiple Select Statements

In the above examples, we have seen multiple SQL insert statements. We’ll now see how to execute multiple SQL select statements in a single call using JDBC. It uses the statement.getMoreResults() method to iterate through the multiple result sets. It is useful when the SQL query contains multiple select statements separated by semicolons, and we want to process each result set individually.

public List<User> executeMultipleSelectStatements() throws SQLException {
    String sql = "SELECT * FROM users WHERE email = '[email protected]';" +
      "SELECT * FROM users WHERE email = '[email protected]';";

    List<User> users = new ArrayList<>();

    try (Statement statement = connection.createStatement()) {
        statement.execute(sql); // Here we execute the multiple queries

        do {
            try (ResultSet resultSet = statement.getResultSet()) {
                while (resultSet != null && resultSet.next()) {
                    int id = resultSet.getInt("id");
                    String name = resultSet.getString("name");
                    String email = resultSet.getString("email");
                    users.add(new User(id, name, email));
                }
            }
        } while (statement.getMoreResults());
    }
    return users;
}

The statement.getMoreResults() method moves the cursor to the next result in the sequence, allowing us to handle multiple result sets sequentially. It returns true if the next result is a ResultSet and false if it is an update count or no more results are available.

We’ll add another test to validate the execution of the multiple SQL select statements and its result:

@Test
public void givenMultipleSelectStatements_whenExecuting_thenCorrectUsersAreFetched() 
  throws SQLException {
    MultipleSQLExecution execution = new MultipleSQLExecution(connection);
    execution.executeMultipleStatements();

    List<User> users = execution.executeMultipleSelectStatements();

    // Here we verify that exactly two users are fetched and their names match the expected ones
    assertThat(users)
      .hasSize(2)
      .extracting(User::getName)
      .containsExactlyInAnyOrder("Alice", "Bob");
}

The above method and the corresponding unit test simplify handling multiple queries in a single database call, ensuring efficient execution and easier result processing.

4. Conclusion

Executing multiple SQL statements in a single JDBC call can enhance performance and code readability. In this tutorial, we explored three different ways to execute multiple SQL statements in JDBC: using the Statement object, batch processing, and stored procedures. Each method has its use case, depending on whether performance or maintainability is the priority.

By understanding these techniques, we can make better decisions about how to structure our database operations and optimize our applications for efficiency and clarity.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)