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()?
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.
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..
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.
Advantages of reuse: You are not discarding as much memory, requires less garbage collection. You only need to update objects that have changed.
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.
Yes, you can. However, it is very much better to use PreparedStatement
to avoid SQL injection vulnerabilities.
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