What is the difference between Statement and PreparedStatement in JDBC?

1 Answers
Answered by suresh

What is the difference between Statement and PreparedStatement in JDBC?

In JDBC, both Statement and PreparedStatement are interfaces used to execute SQL queries. However, there are some key differences between the two:

  1. Execution:
    • Statement: Executes a single SQL query when it is called.
    • PreparedStatement: Pre-compiles the SQL query and can be reused with different parameters.
  2. Performance:
    • Statement: Compiles the SQL query every time it is executed, which can impact performance.
    • PreparedStatement: Pre-compiles the SQL query only once, improving performance when executed multiple times with different parameters.
  3. SQL Injection:
    • Statement: Prone to SQL injection attacks if user input is not properly sanitized.
    • PreparedStatement: Uses parameterized queries to prevent SQL injection attacks.

Overall, PreparedStatement is preferred over Statement in JDBC for its performance benefits and protection against SQL injection.

Answer for Question: What is the difference between Statement and PreparedStatement in JDBC?