Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute multiple queries using a single JDBC Statement object

Tags:

java

sql

mysql

jdbc

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); } 
like image 836
Syed Aqeel Ashiq Avatar asked Jan 24 '14 07:01

Syed Aqeel Ashiq


People also ask

Which method is used to execute multiple queries using a statement object stmt '?

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.

How run multiple SQL queries in Java?

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.


1 Answers

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

like image 173
Durandal Avatar answered Sep 17 '22 18:09

Durandal