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…
Section overview
5 resourcesCovers 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
- Write a program to update the age of a student in the database using
PreparedStatement. - Write a program to delete all students who are under 18 years old using
PreparedStatement. - 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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article