JDBC PreparedStatement Interface
The PreparedStatement class extends the Statement interface within the java.sql package. The PreparedStatement object allows developers to run parameterized SQL queries in a way that maximizes performance and security. A PreparedStatement differs from Statement because it uses precompilation which results in quicker execution and protection against SQL injection attacks.
Why Use PreparedStatement?
- Prevents SQL Injection
- Improves performance with repeated queries
- Allows dynamic parameters
- Supports batch execution
Package & Declaration
import java.sql.PreparedStatement;
PreparedStatement ps = connection.prepareStatement("SQL QUERY");
| Method | Description |
|---|---|
| setInt(int parameterIndex, int) | Sets int value at specified position |
| setString(int parameterIndex, String) | Sets String value at position |
| executeQuery() | Executes SELECT query, returns ResultSet |
| executeUpdate() | Executes INSERT/UPDATE/DELETE, returns row count |
| addBatch() / executeBatch() | Used for batch operations |
| close() | Closes the PreparedStatement |
Example
import java.sql.*;
public class PreparedStatementExample {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb", "root", "password");
String sql = "SELECT * FROM employees WHERE id = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, 2); // Bind value to placeholder
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt("id") + " - " + rs.getString("name"));
}
rs.close();
ps.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Best Practices
- Always choose PreparedStatement when working with user inputs instead of Statement.
- Always close the statement after use
- Use batch execution for bulk operations
- Use try-with-resources to auto-close resources
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com