![]() |
VOOZH | about |
A PreparedStatement in Java is a pre-compiled SQL statement. It is a subinterface of Statement, but comes with additional benefits like improved performance, cleaner code and protection against SQL injection attacks. Instead of hardcoding values into SQL queries, PreparedStatement allows you to use placeholders (?) that can be set dynamically at runtime.
Connection myCon = DriverManager.getConnection(url, username, password)
Instead of hardcoding queries like,
SELECT * FROM students WHERE age > 10 AND name = 'Chhavi';
Set parameter placeholders(use question mark for placeholders) like,
select * from students where age> ? and name = ?
PreparedStatement myStmt;
myStmt = myCon.prepareStatement("SELECT * FROM students WHERE age > ? AND name = ?");
Each ? corresponds to a parameter index starting from 1.
myStmt.setInt(1,10);
myStmt.setString(2,"Chhavi");
ResultSet myRs = myStmt.executeQuery(); // For SELECT queries
int rowsAffected = myStmt.executeUpdate(); // For INSERT, UPDATE, DELETE
while (myRs.next()) {
int id = myRs.getInt("id");
String name = myRs.getString("name");
int age = myRs.getInt("age");
// Process the retrieved data
}
myRs.close();
myStmt.close();
myCon.close();
We will work on a table named students with the following structure and sample data:
After insertion, the table will look like this:
4.1 SELECT Query Example
Output:
4.2 INSERT Query Example
Output:
Updated table:
Note:
Class.forName("org.apache.derby.jdbc.ClientDriver"); is needed only for older JDBC versions (pre-4.0). In JDBC 4.0+, drivers are auto-loaded if the correct JDBC JAR is in the classpath. If you get a No suitable driver error, check that the proper driver dependency is added.