Execute multiple queries using a single JDBC Statement object

前端 未结 5 2062
说谎
说谎 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:06

    I am not sure why you are asking. The API design and documentation show it is perfectly fine (and even intended) to reuse a Statement object for multiple execute, executeUpdate and executeQuery calls. If it wouldn't be allowed that would be explicitly documented in the Java doc (and likely the API would be different).

    Furthermore the apidoc of Statement says:

    All execution methods in the Statement interface implicitly close a statment's [sic] current ResultSet object if an open one exists.

    This is an indication that you can use it multiple times.

    TL;DR: Yes, you can call execute on single Statement object multiple times, as long as you realize that any previously opened ResultSet will be closed.

    Your example incorrectly uses PreparedStatement, and you cannot (or: should not) be able to call any of the execute... methods accepting a String on a PreparedStatement:

    SQLException - if [...] the method is called on a PreparedStatement or CallableStatement

    But to answer for PreparedStatement as well: the whole purpose of a PreparedStatement is to precompile a statement with parameter placeholders and reuse it for multiple executions with different parameter values.

提交回复
热议问题