12. Can you explain the difference between Statement, PreparedStatement, and CallableStatement in JDBC?

Basic

12. Can you explain the difference between Statement, PreparedStatement, and CallableStatement in JDBC?

Overview

In JDBC (Java Database Connectivity), understanding the difference between Statement, PreparedStatement, and CallableStatement is crucial for executing SQL queries efficiently and securely. These interfaces provide mechanisms to interact with the database, each serving different purposes and offering various levels of performance and security.

Key Concepts

  1. Statement: Used for executing a simple SQL query with no parameters.
  2. PreparedStatement: Allows pre-compilation and parameterized SQL queries, enhancing performance and security.
  3. CallableStatement: Used for executing stored procedures that may return results.

Common Interview Questions

Basic Level

  1. What is the difference between Statement and PreparedStatement in JDBC?
  2. How do you use a PreparedStatement to execute a SQL query?

Intermediate Level

  1. Explain how CallableStatement is used to call stored procedures in JDBC.

Advanced Level

  1. Discuss the performance implications of using PreparedStatement over Statement.

Detailed Answers

1. What is the difference between Statement and PreparedStatement in JDBC?

Answer: The primary difference lies in performance and security. Statement is used for executing simple SQL queries without parameters. It poses a risk of SQL injection and typically performs slower for repeated executions. PreparedStatement, on the other hand, allows for SQL pre-compilation and parameterization, significantly improving performance for repeated queries and enhancing security by preventing SQL injection.

Key Points:
- Statement is suitable for executing SQL queries that do not require input parameters.
- PreparedStatement offers performance benefits by pre-compiling SQL queries and allows secure insertion of parameters.
- PreparedStatement prevents SQL injection through parameterized queries.

Example:

// Assuming connection is a valid, open JDBC connection
String query = "SELECT * FROM users WHERE id = ?";
try (PreparedStatement pstmt = connection.prepareStatement(query)) {
    pstmt.setInt(1, 10); // Setting parameter at index 1
    ResultSet rs = pstmt.executeQuery();
    while(rs.next()) {
        // Process the results
    }
} catch (SQLException e) {
    e.printStackTrace();
}

2. How do you use a PreparedStatement to execute a SQL query?

Answer: PreparedStatement is used by first preparing the SQL query with placeholders for parameters. These placeholders are then filled with actual values through setter methods before executing the query.

Key Points:
- Initialize PreparedStatement with a parameterized SQL query.
- Use setter methods (e.g., setInt, setString) to insert values into placeholders.
- Execute the query using executeQuery for SELECT or executeUpdate for INSERT, UPDATE, DELETE.

Example:

String insertQuery = "INSERT INTO employees(name, department) VALUES (?, ?)";
try (PreparedStatement pstmt = connection.prepareStatement(insertQuery)) {
    pstmt.setString(1, "John Doe");
    pstmt.setString(2, "HR");
    int affectedRows = pstmt.executeUpdate();
    System.out.println("Inserted rows: " + affectedRows);
} catch (SQLException e) {
    e.printStackTrace();
}

3. Explain how CallableStatement is used to call stored procedures in JDBC.

Answer: CallableStatement is specifically designed to call stored procedures in a database. It can handle IN, OUT, and INOUT parameters and can execute stored procedures that return result sets.

Key Points:
- CallableStatement is created by calling prepareCall with SQL calling the stored procedure.
- Parameters (IN, OUT, INOUT) can be set and registered prior to execution.
- Stored procedures can return multiple result sets and output parameters.

Example:

String callProcedure = "{CALL getSalariedEmployees(?)}";
try (CallableStatement cstmt = connection.prepareCall(callProcedure)) {
    cstmt.registerOutParameter(1, Types.INTEGER);
    cstmt.execute();
    int count = cstmt.getInt(1); // Retrieve the output parameter
    System.out.println("Salaried Employees Count: " + count);
} catch (SQLException e) {
    e.printStackTrace();
}

4. Discuss the performance implications of using PreparedStatement over Statement.

Answer: PreparedStatement offers significant performance improvements over Statement, especially in scenarios where the same SQL query is executed multiple times with different parameters. This performance gain is due to the pre-compilation of SQL queries in PreparedStatement, which eliminates the need for the database to compile the SQL query every time it is executed. Moreover, PreparedStatement reduces parsing overhead and improves batch update performance.

Key Points:
- Pre-compilation of SQL queries in PreparedStatement enhances performance.
- Reduced parsing overhead and database compilation time.
- Efficient handling of batch updates and parameterized queries.

Example:

// Using PreparedStatement for batch updates
String updateQuery = "UPDATE employees SET salary = salary * 1.1 WHERE department = ?";
try (PreparedStatement pstmt = connection.prepareStatement(updateQuery)) {
    String[] departments = {"HR", "IT", "Sales"};
    for (String dept : departments) {
        pstmt.setString(1, dept);
        pstmt.addBatch();
    }
    int[] updateCounts = pstmt.executeBatch();
    System.out.println("Updated rows: " + Arrays.toString(updateCounts));
} catch (SQLException e) {
    e.printStackTrace();
}

This comprehensive guide covers the essential differences and use cases of Statement, PreparedStatement, and CallableStatement in JDBC, providing a solid foundation for interview preparation on this topic.