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



Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.