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
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] currentResultSet
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 aPreparedStatement
orCallableStatement
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.