Skip to content
C

PreparedStatement

PreparedStatement is a JDBC interface used to run SQL queries that include placeholders (?) for values, which are filled in safely and separately from the SQL text itself.


1. What is PreparedStatement?

PreparedStatement is a JDBC interface used to run SQL queries that include placeholders (?) for values, which are filled in safely and separately from the SQL text itself.

2. Why is it used?

It protects against SQL injection attacks by keeping user-provided values separate from the actual SQL command structure, and it also allows the same query structure to be reused efficiently with different values.

3. Real-Life Example

Think of a fill-in-the-blanks form, like "Dear __, your order number is __," where the blanks are safely filled in with specific details each time, without altering the fixed structure of the form itself.

4. Syntax

java
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM students WHERE id = ?"); pstmt.setInt(1, studentId); ResultSet rs = pstmt.executeQuery();

5. Example Program

java
import java.sql.*; public class PreparedStatementDemo { public static void main(String[] args) throws SQLException { Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/schooldb", "root", "password" ); PreparedStatement pstmt = conn.prepareStatement( "SELECT name FROM students WHERE id = ?" ); pstmt.setInt(1, 101); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { System.out.println(rs.getString("name")); } conn.close(); } }

Output:

Aditi

(Actual output depends on the real data present for the given student id.)

6. Key Points to Remember

  • Placeholders (?) are filled in using methods like setInt(), setString(), matching the position number (starting from 1).
  • PreparedStatement protects against SQL injection, unlike plain Statement.
  • It's the generally recommended choice for real-world applications whenever queries involve external input.