Introduction
When working with databases in Java, executing SQL queries safely and efficiently is essential. JDBC provides different interfaces to execute SQL statements, and one of the most commonly used is PreparedStatement. It is an improved version of the Statement interface that supports parameterized SQL queries, making applications more secure, efficient, and easier to maintain.
Unlike the Statement interface, which directly executes SQL queries, PreparedStatement allows developers to use placeholders (?) for input values. These values are supplied separately, helping prevent SQL injection attacks and improving performance by allowing the database to precompile SQL statements.
In modern Java applications, PreparedStatement is the preferred choice for executing INSERT, SELECT, UPDATE, and DELETE operations. It is widely used in enterprise applications, web applications, banking systems, e-commerce platforms, and almost every JDBC-based project.
What is PreparedStatement?
PreparedStatement is an interface in the java.sql package that extends the Statement interface. It is used to execute precompiled, parameterized SQL statements.
Instead of directly inserting values into an SQL query, placeholders (?) are used. The actual values are supplied later using setter methods such as setInt(), setString(), setDouble(), and more.
Because the SQL statement is compiled once and reused multiple times with different parameter values, PreparedStatement offers better performance and enhanced security.
Why Use PreparedStatement?
There are several reasons to prefer PreparedStatement over Statement.
- Prevents SQL injection attacks.
- Improves performance by precompiling SQL.
- Supports parameterized queries.
- Handles special characters automatically.
- Makes code easier to read and maintain.
- Allows the same SQL statement to be executed multiple times with different values.
Syntax
The general syntax of PreparedStatement is:
Connection con = DriverManager.getConnection(url, username, password);
String sql = "SELECT * FROM employee WHERE id = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, 101);
ResultSet rs = ps.executeQuery();
The ? symbol is called a parameter placeholder.
How PreparedStatement Works
The following steps explain how PreparedStatement works.
- Establish a database connection.
- Write a parameterized SQL query using ?.
- Create a PreparedStatement object.
- Assign values using setter methods.
- Execute the SQL statement.
- Process the result.
- Close all database resources.
Common Setter Methods
The following methods are commonly used to assign parameter values.
| Method | Description |
|---|---|
| setInt() | Sets an integer value |
| setDouble() | Sets a double value |
| setFloat() | Sets a float value |
| setBoolean() | Sets a boolean value |
| setDate() | Sets a SQL date |
| setLong() | Sets a long value |
Example:
ps.setInt(1, 101);
ps.setString(2, "Rahul");
ps.setDouble(3, 55000);
Example 1: Insert Data Using PreparedStatement
Suppose we have the following table.
CREATE TABLE employee(
id INT PRIMARY KEY,
name VARCHAR(100),
department VARCHAR(50),
salary DOUBLE
);
Java program:
import java.sql.*;
public class InsertEmployee {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/company";
String username = "root";
String password = "password";
try
Connection con = DriverManager.getConnection(url, username, password);
String sql = "INSERT INTO employee VALUES(?,?,?,?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1,101);
ps.setString(2,"Rahul");
ps.setString(3,"IT");
ps.setDouble(4,55000);
int rows = ps.executeUpdate()
System.out.println(rows + " Record Inserted.");
ps.close();
con.close();
} catch(Exception e){
e.printStackTrace();
}
}
}
Output
Example 2: Retrieve Data Using PreparedStatement
import java.sql.*;
public class SelectEmployee
public static void main(String[] args) {
try {
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/company",
"root",
"password");
String sql = "SELECT * FROM employee WHERE department=?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1,"IT");
ResultSet rs = ps.executeQuery();
while(rs.next()){
System.out.println(
rs.getInt("id")+" "+
rs.getString("name")+" "+
rs.getDouble("salary"));
}
rs.close();
ps.close();
con.close();
} catch(Exception e){
e.printStackTrace();
}
}
}
Example 3: Update Data
String sql = "UPDATE employee SET salary=? WHERE id=?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setDouble(1,60000);
ps.setInt(2,101);
int rows = ps.executeUpdate();
Example 4: Delete Data
String sql = "DELETE FROM employee WHERE id=?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1,01);
int rows = ps.executeUpdate();
Frequently Used Methods
| Method | Description |
|---|---|
| executeQuery() | Executes a SELECT query |
| executeUpdate() | Executes INSERT, UPDATE, or DELETE |
| execute() | Executes any SQL statement |
| clearParameters() | Clears parameter values |
| close() | Closes the PreparedStatement |
| setObject() | Sets any Java object as a parameter |
PreparedStatement Workflow
Java Application
│
▼
Database Connection
│
▼
Prepare SQL Statement
│
▼
Set Parameter Values
│
▼
Execute SQL
│
▼
Database
│
▼
Return Result
PreparedStatement vs Statement
| Feature | Statement | PreparedStatement |
|---|---|---|
| SQL Injection Protection | No | Yes |
| Performance | Lower | Better |
| Parameterized Queries | No | Yes |
| Reusability | Limited | High |
| Readability | Lower | Better |
| Recommended | No | Yes |
Advantages of PreparedStatement
Using PreparedStatement provides several benefits:
- Prevents SQL injection attacks.
- Improves execution speed for repeated queries.
- Supports parameterized SQL.
- Handles special characters automatically.
- Reduces syntax errors.
- Produces cleaner and more maintainable code.
- Suitable for enterprise applications.
- Compatible with all major relational databases.
Real-life Example
Consider an Online Banking System.
When a customer logs in, they enter their account number.
The SQL query is:
SELECT * FROM customer WHERE account_number = ?
Instead of building the query by concatenating user input, the application uses PreparedStatement to pass the account number safely as a parameter. This prevents attackers from injecting malicious SQL and ensures secure access to customer data.
Similarly, PreparedStatement is widely used in:
- E-commerce websites
- Hospital management systems
- Student management systems
- Hotel booking systems
- Inventory management systems
- Payroll applications
Best Practices
Follow these best practices when using PreparedStatement:
- Always use parameterized queries instead of string concatenation.
- Prefer PreparedStatement over Statement.
- Use try-with-resources to automatically close JDBC resources.
- Validate user input before executing SQL statements.
- Store database credentials in configuration files or environment variables.
- Use transactions for multiple related database operations.
- Handle SQLException appropriately and log meaningful error messages.
- Reuse PreparedStatement objects when executing the same SQL multiple times.
Common Mistakes
Avoid these common mistakes:
- Using Statement for user input.
- Forgetting to set parameter values before execution.
- Setting parameters in the wrong order.
- Using an incorrect data type in setter methods.
- Not closing PreparedStatement objects.
- Ignoring SQL exceptions.
- Building SQL queries using string concatenation.
- Forgetting to check the number of affected rows after executeUpdate().
Conclusion
PreparedStatement is one of the most important interfaces in JDBC and is the recommended way to execute SQL statements in Java. It improves security by preventing SQL injection, enhances performance through precompiled SQL statements, and makes code more readable and maintainable.
Whether you are inserting, retrieving, updating, or deleting records, using PreparedStatement ensures that your Java applications are secure, efficient, and scalable. Mastering this interface is an essential step toward building professional database-driven applications and prepares you for advanced JDBC topics such as batch processing, transactions, stored procedures, and connection pooling.