Using Prepared Statements in Java with Examples
#Using Prepared Statements in Java with Examples
Introduction
When working with databases in Java, executing SQL queries securely and efficiently is crucial. The PreparedStatement interface in JDBC is a powerful tool that helps developers write parameterized queries, improve performance, and prevent SQL injection attacks. Unlike the Statement
interface, PreparedStatements are precompiled by the database, making them faster and more secure.
In this article, we’ll learn how to use PreparedStatement in Java with examples for SELECT, INSERT, UPDATE, and DELETE queries.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb", "root", "password");
PreparedStatement pstmt = con.prepareStatement(
"INSERT INTO users (id, name) VALUES (?, ?)"
);
pstmt.setInt(1, 1);
pstmt.setString(2, "John");
int rowsInserted = pstmt.executeUpdate();
System.out.println(rowsInserted + " row(s) inserted.");
con.close();
pstmt.close();
PreparedStatement pstmt = con.prepareStatement("INSERT INTO users (id, name) VALUES (?, ?)");
pstmt.setInt(1, 2);
pstmt.setString(2, "Alice");
pstmt.executeUpdate();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM users WHERE id = ?");
pstmt.setInt(1, 1);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}
PreparedStatement pstmt = con.prepareStatement("UPDATE users SET name = ? WHERE id = ?");
pstmt.setString(1, "Michael");
pstmt.setInt(2, 1);
pstmt.executeUpdate();
PreparedStatement pstmt = con.prepareStatement("DELETE FROM users WHERE id = ?");
pstmt.setInt(1, 2);
pstmt.executeUpdate();
✅ Security: Protects against SQL injection attacks.
✅ Performance: Queries are precompiled and reused by the database.
✅ Readability: Code is cleaner and easier to maintain.
✅ Parameterization: Supports dynamic query execution with placeholders (?
).
import java.sql.*;
public class PreparedStatementDemo {
public static void main(String[] args) {
try {
// Step 1: Establish Connection
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb", "root", "password");
// Step 2: Create PreparedStatement
PreparedStatement pstmt = con.prepareStatement("INSERT INTO users (id, name) VALUES (?, ?)");
// Step 3: Set Parameters
pstmt.setInt(1, 3);
pstmt.setString(2, "Emma");
// Step 4: Execute Update
int rows = pstmt.executeUpdate();
System.out.println(rows + " row(s) inserted.");
// Close connection
pstmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Always close ResultSet, PreparedStatement, and Connection.
Use try-with-resources for automatic resource management.
Prefer PreparedStatement over Statement to avoid SQL injection.
Use batch processing when inserting/updating multiple records.
Using PreparedStatement in Java is the recommended way to execute SQL queries. It ensures better performance, security, and cleaner code compared to the traditional Statement
interface. By following the examples and best practices, you can build efficient and secure database-driven Java applications.
🔑 Target SEO Keywords:
PreparedStatement in Java, JDBC PreparedStatement example, prevent SQL injection Java, Java SQL queries, JDBC tutorial, execute SQL in Java securely.