Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Statement Object Reuse?

Tags:

java

jdbc

I would like to know if we can reuse the same Statement object for executing more than one query. Or, should we create a new statement for different queries.

For example,

Connection con = getDBConnection(); Statement st1 = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); int i = st1.executeUpdate("update tbl_domu set domU_status=1 where domU_id=" + dom_U_id); Statement st2 = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()); int j = st2.executeUpdate("insert into tbl_domU_action_history values('" + dom_U_name + "', 1, '" + date + "')");   

In the above case, is there any harm in using the same statement st1 for both the executeUpdate() queries? Can I use the same Statement object st1 for another executeQuery()?

like image 792
Epitaph Avatar asked Dec 23 '08 19:12

Epitaph


People also ask

Can I reuse a prepared statement?

Reusing a PreparedStatementOnce a PreparedStatement is prepared, it can be reused after execution. You reuse a PreparedStatement by setting new values for the parameters and then execute it again.

How to reuse ResultSet Java?

If you want to test, whether your resultset gets closed or not, you can use a while loop to iterate over the result set and inside the while loop, create another query and assign it to same result set. You will see that an Exception will be thrown..

Can we use same prepared statement for multiple queries?

Statement interface can be used to execute static SQL queries whereas PreparedStatement interface is used to execute dynamic SQL queries multiple times. In this example, the java.

Which is the advantage of reusing existing objects?

Advantages of reuse: You are not discarding as much memory, requires less garbage collection. You only need to update objects that have changed.


2 Answers

I came across the response I was looking for in the Javadocs

By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects.

like image 175
Epitaph Avatar answered Oct 07 '22 16:10

Epitaph


Yes, you can. However, it is very much better to use PreparedStatement to avoid SQL injection vulnerabilities.

like image 43
Tom Hawtin - tackline Avatar answered Oct 07 '22 15:10

Tom Hawtin - tackline