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 query, and create new object for executing another query.
E.G:
Connection con; Statement s; ResultSet rs; ResultSet rs2; try { con = getConnection(); s = con.prepareStatement(); try { rs = s.executeQuery("......................."); // process the result set rs } finally { close(rs); } // I know what to do to rs here // But I am asking, should I close the Statement s here? Or can I use it again for the next query? try { rs2 = s.executeQuery("......................."); // process the result set rs2 } finally { close(rs2); } } finally { close(s); close(con); }
The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together.
Demonstrating execution of multiple SQL commands on a database simultaneously using the addBatch() and executeBatch() commands of JDBC. The addBatch() command is used to queue the SQL statements and executeBatch() command is used to execute the queued SQL statements all at once.
Yes you can re-use a Statement
(specifically a PreparedStatement
) and should do so in general with JDBC. It would be inefficient & bad style if you didn't re-use your statement and immediately created another identical Statement
object. As far as closing it, it would be appropriate to close it in a finally block, just as you are in this snippet.
For an example of what you're asking check out this link: jOOq Docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With