Working with PreparedStatement and Batch Updates

Tutorial 3 of 5

1. Introduction

In this tutorial, we will explore how to use the PreparedStatement interface in Java to execute dynamic SQL queries. We will also learn how to use batch updates to group related SQL statements, which can significantly improve performance when dealing with large data sets.

By the end of this tutorial, you will be able to:
- Understand and use the PreparedStatement interface
- Use batch updates to efficiently execute multiple SQL statements
- Write clean, efficient, and secure database code

Prerequisites:
- Basic understanding of Java programming language
- Basic knowledge of SQL
- A working Java development environment (like IntelliJ IDEA or Eclipse) with JDBC driver installed

2. Step-by-Step Guide

2.1 PreparedStatement

PreparedStatement is a Java interface that extends Statement. It represents a precompiled SQL statement which can be executed multiple times without the overhead of compiling it for each execution. It's more efficient and secure, especially when dealing with user input.

2.2 Batch Updates

Batch updates allow you to group related SQL statements into a batch and execute them together. This reduces the number of round-trip calls between your Java program and the database, thereby improving performance.

3. Code Examples

3.1 Using PreparedStatement

import java.sql.*;

public class Main {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/test";
        String user = "root";
        String password = "root";

        try (Connection con = DriverManager.getConnection(url, user, password)) {
            String query = "INSERT INTO students (name, age) VALUES (?, ?)";
            PreparedStatement stmt = con.prepareStatement(query);
            stmt.setString(1, "John");
            stmt.setInt(2, 18);
            int rows = stmt.executeUpdate();
            System.out.println("Rows inserted: " + rows);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}

In the above code:
- We establish a connection to the database.
- We create a PreparedStatement with a SQL query. The ? are placeholders for parameters.
- We set the parameters using appropriate set methods.
- We execute the statement using executeUpdate(), which returns the number of affected rows.
- If everything goes well, it should print "Rows inserted: 1".

3.2 Using Batch Updates

import java.sql.*;

public class Main {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/test";
        String user = "root";
        String password = "root";

        try (Connection con = DriverManager.getConnection(url, user, password)) {
            con.setAutoCommit(false); // disable auto-commit
            String query = "INSERT INTO students (name, age) VALUES (?, ?)";
            PreparedStatement stmt = con.prepareStatement(query);

            // first student
            stmt.setString(1, "John");
            stmt.setInt(2, 18);
            stmt.addBatch();

            // second student
            stmt.setString(1, "Jane");
            stmt.setInt(2, 19);
            stmt.addBatch();

            int[] rows = stmt.executeBatch();
            con.commit(); // commit changes

            System.out.println("Rows inserted: " + rows.length);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}

In this example, we:
- Disable auto-commit to manually control when changes are committed
- Add multiple sets of parameters to the PreparedStatement
- Use executeBatch() to execute all statements at once
- Commit the changes with commit()
- If successful, it will print "Rows inserted: 2"

4. Summary

In this tutorial, we learned how to:
- Use PreparedStatement to execute dynamic SQL queries
- Utilize batch updates to group related SQL statements and improve performance

Keep practicing these concepts. You can also read more about Statement, PreparedStatement, and Batch Updates in the Java documentation.

5. Practice Exercises

  1. Write a program to update the age of a student in the database using PreparedStatement.
  2. Write a program to delete all students who are under 18 years old using PreparedStatement.
  3. Write a program to insert 5 different students into the database using batch updates.

Solutions and explanations to these exercises can be found by combining the concepts explained in the tutorial. For further practice, try to solve more complex tasks or implement these concepts in your project.