Execute multiple queries using a single JDBC Statement object

前端 未结 5 2058
说谎
说谎 2021-01-31 17:41

In JDBC, can I use single Statement object to call executeQuery(\"\") multiple times? Is it safe? Or should I close the statement object after each que

5条回答
  •  醉梦人生
    2021-01-31 18:03

    A Prepared Statement tells the database to remember your query and to be prepared to accept parameterized variables to execute in that query. It's a lot like a stored procedure.

    Prepared Statement accomplishes two main things:

    1. It automatically escapes your query variables to help guard against SQL Injection.

    2. It tells the database to remember the query and be ready to take variables.

    Number 2 is important because it means the database only has to interpret your query once, and then it has the procedure ready to go. So it improves performance.

    You should not close a prepared statement and/or the database connection in between execute calls. Doing so is incredibly in-efficient and it will cause more overhead than using a plain old Statement since you instruct the database each time to create a procedure and remember it. Even if the database is configured for "hot spots" and remembers your query anyways even if you close the PreparedStatement, you still incur network overhead as well as small processing time.

    In short, keep the Connection and PreparedStatement open until you are done with them.

    Edit: To comment on not returning a ResultSet from the execution, this is fine. executeQuery will return the ResultSet for whatever query just executed.

提交回复
热议问题