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
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:
It automatically escapes your query variables to help guard against SQL Injection.
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.