Java / Java Database Connectivity (JDBC)

Working with PreparedStatement and Batch Updates

In this tutorial, we will delve into using the PreparedStatement interface for executing dynamic SQL queries. We will also cover how to use batch updates to group related SQL stat…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Covers database interaction with JDBC API for connecting, querying, and updating databases.

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.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

CSV to JSON Converter

Convert CSV files to JSON format and vice versa.

Use tool

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

Time Zone Converter

Convert time between different time zones.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help