JDBC Tutorial - JDBC PreparedStatement








PreparedStatement is used to execute the SQL statements many times.

The PreparedStatement interface accepts input parameters at runtime.

The PreparedStatement interface extends the Statement interface.

We can supply arguments dynamically for PreparedStatement.

Example

The following code shows how to create PreparedStatement Object.

PreparedStatement pstmt = null;
try {
   String SQL = "Update Employees SET age = ? WHERE id = ?";
   pstmt = conn.prepareStatement(SQL);
   . . .
}
catch (SQLException e) {
   . . .
}
finally {
   . . .
}




Parameters in PreparedStatement

All parameters in JDBC are represented by the ? symbol.

? is known as the parameter marker.

We must supply values for every parameter before executing the SQL statement.

The setXXX() methods from PreparedStatement bind values to the parameters, where XXX represents the Java data type.

Unlike the Java array or List in collection framework. The index of parameters in PreparedStatement starts from position 1.

Close PreparedStatement Obeject

We need to close PreparedStatement object to free up the resource allocated for it.

Closing the Connection object will close the PreparedStatement object as well.

PreparedStatement pstmt = null;
try {
   String SQL = "Update Employees SET age = ? WHERE id = ?";
   pstmt = conn.prepareStatement(SQL);
}
catch (SQLException e) {
}
finally {
   pstmt.close();
}