Overview
JDBC (Java Database Connectivity) is a pivotal Java API for connecting and executing operations in the database. Understanding the difference between Statement
, PreparedStatement
, and CallableStatement
is crucial for efficiently managing database operations, ensuring data security, and optimizing performance in Java applications.
Key Concepts
- Statement: Used for executing simple SQL queries without parameters.
- PreparedStatement: Extends
Statement
, precompiles SQL queries, and allows the use of input parameters, enhancing performance and security. - CallableStatement: Extends
PreparedStatement
, used for executing stored procedures that can return results.
Common Interview Questions
Basic Level
- What is the difference between
Statement
andPreparedStatement
in JDBC? - How do you use a
PreparedStatement
to insert data into a database?
Intermediate Level
- Why is
PreparedStatement
preferred overStatement
in JDBC?
Advanced Level
- How can you use a
CallableStatement
to execute a stored procedure that returns multiple results?
Detailed Answers
1. What is the difference between Statement
and PreparedStatement
in JDBC?
Answer:
Statement
is used for executing a simple SQL query without parameters. It is compiled every time it's executed. PreparedStatement
, on the other hand, represents a precompiled SQL statement that can be executed multiple times with different input parameters, improving performance and security by preventing SQL injection attacks.
Key Points:
- Statement
is less efficient for repeated executions of similar SQL queries.
- PreparedStatement
improves performance by reducing the time needed for query compilation.
- PreparedStatement
enhances security by allowing parameterized queries.
Example:
// Using Statement
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users WHERE userId = 1");
// Using PreparedStatement
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users WHERE userId = ?");
pstmt.setInt(1, 1);
ResultSet rs = pstmt.executeQuery();
2. How do you use a PreparedStatement
to insert data into a database?
Answer:
To use a PreparedStatement
for inserting data, create a precompiled SQL statement with placeholders for values, set these values using appropriate setter methods (e.g., setInt
, setString
), and execute the statement.
Key Points:
- Use placeholders ?
for parameters to prevent SQL injection.
- Call appropriate setter methods based on data type.
- Use executeUpdate()
for insertion.
Example:
String query = "INSERT INTO users(name, email) VALUES(?, ?)";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, "John Doe");
pstmt.setString(2, "john.doe@example.com");
int affectedRows = pstmt.executeUpdate();
3. Why is PreparedStatement
preferred over Statement
in JDBC?
Answer:
PreparedStatement
is preferred over Statement
primarily for two reasons: performance optimization and security. Precompilation and reusable query plan of PreparedStatement
make it faster for executing similar SQL queries multiple times. Its support for parameterized queries helps prevent SQL injection attacks, making applications more secure.
Key Points:
- Performance benefit from precompilation.
- Security enhancement through parameterization.
- Reduces parsing time as SQL statement is compiled only once.
Example:
Refer to the examples provided in questions 1 and 2 for code illustrations.
4. How can you use a CallableStatement
to execute a stored procedure that returns multiple results?
Answer:
A CallableStatement
is used to execute stored procedures. To handle multiple results, use methods like execute
, getResultSet
, and getMoreResults
. After executing the CallableStatement
, loop through the results using getMoreResults
and getResultSet
to process each.
Key Points:
- Use CallableStatement
for stored procedures.
- Handle multiple results or update counts.
- Loop with getMoreResults
and getResultSet
.
Example:
CallableStatement cstmt = conn.prepareCall("{call GetEmployeeDetails(?)}");
cstmt.setInt(1, 1001); // Setting parameter value
boolean hasResults = cstmt.execute();
while (hasResults) {
ResultSet rs = cstmt.getResultSet();
while (rs.next()) {
// Process result set
}
rs.close();
hasResults = cstmt.getMoreResults(); // Check for more results
}
This guide covers the essentials of using Statement
, PreparedStatement
, and CallableStatement
in JDBC, providing a solid foundation for interview preparation.