Middle
What types of Statements exist in JDBC?
sobes.tech AI
Answer from AI
There are three main types of Statement in JDBC:
-
Statement:- Suitable for executing static SQL queries without parameters.
- Does not cache the execution plan, which can reduce performance when executing repeatedly.
- Vulnerable to SQL injection as values are inserted directly into the query string.
-
PreparedStatement:- Designed for executing parameterized SQL queries.
- Parameters are set using
setXXX()methods. - Caches the execution plan, improving performance for multiple calls with different parameters.
- Safe from SQL injection as parameters are automatically escaped.
-
CallableStatement:- Used for calling stored procedures and functions in the database.
- Supports input, output, and input/output parameters.
- Parameters are set and registered using
setXXX()andregisterOutParameter()methods.
Example of using PreparedStatement:
// Connecting to the database (assuming the connection "conn" is established)
String sql = "SELECT name, age FROM users WHERE id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, 101); // Setting the parameter for WHERE id = ?
try (ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
System.out.println("Name: " + rs.getString("name") + ", Age: " + rs.getInt("age"));
}
}
} catch (SQLException e) {
e.printStackTrace();
}