when to use Statement over Prepared Statement?

前端 未结 2 1468
傲寒
傲寒 2021-02-04 14:05

When to use statement instead of prepared statement. i suppose statement is used in queries with no parameter but why not use prepared statement ? Which one is faster for querie

2条回答
  •  北荒
    北荒 (楼主)
    2021-02-04 14:38

    That's depending on Your requirement.

    If you have a SQL statement which runs in a loop or frequently with different parameters then PreparedStatement is the best candidate since it is getting pre-compiled and cache the execution plan for this parameterized SQL query. Each time it runs from the same PreparedStatement object it will use cached execution plan and gives the better performance.

    Also SQL injection can be avoided using PreparedStatement .

    But if you are sure that you run SQL query only once, sometimes Statement will be the best candidate since when you create PreparedStatement object sometimes it make additional db call, if the driver supports precompilation, the method Connection.prepareStatement(java.lang.String) will send the statement to the database for precompilation.

    Read below article to understand "Statement Versus PreparedStatement"

    • Java Programming with Oracle JDBC

提交回复
热议问题