Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I close statements in a transaction before committing it in Derby (JDBC)?

Tags:

Basically I have (ignoring exception handling, etc.):

connection.setAutoCommit(false);  Statement statement1 = connection.createStatement(); statement1.executeUpdate("..."); statement1.close();  Statement statement2 = connection.createStatement(); statement2.executeUpdate("..."); statement2.close();  connection.commit(); 

If I understand correctly it shouldn't have any impact because all it really does is free the resources for the GC. Especially with Derby: You should explicitly close Statements, ResultSets, and Connections when you no longer need them. Connections to Derby are resources external to an application, and the garbage collector will not close them automatically.

However will it cause any issues with the transaction? I don't believe the transaction relies on the Statement. Can anyone please confirm this?

like image 417
Stephane Grenier Avatar asked Nov 24 '11 04:11

Stephane Grenier


People also ask

Do I need to close statement JDBC?

JDBC Statement objects must always be explicitly closed by calling the close method on the object. This also applies to the PreparedStatement and CallableStatement objects.

When should I close PreparedStatement?

Closing PreparedStatement Object A simple call to the close() method will do the job. If you close the Connection object first, it will close the PreparedStatement object as well. However, you should always explicitly close the PreparedStatement object to ensure proper cleanup.

Does closing statement close ResultSet?

closing the Statement automatically closes any open ResultSet created from it; executing SQL on a Statement also closes any previously-open ResultSet on that statement.

Why is it necessary to call close () on JDBC objects before they go out of scope?

If you're reusing a connection for multiple statements, closing statements before they go out of scope allows the server to clean up the prepared handles earlier.


2 Answers

Absolutely, you can close them, and you should.

like image 101
勿绮语 Avatar answered Sep 22 '22 15:09

勿绮语


Generally speaking, once a Statement is executed, the underlying datasource/database is responsible for ensuring successful execution. Any failures are expected to result in SQLExceptions being thrown in the Statement.executeXXX invocations. And any successful execution would result in the database tracking these updates in a temporary working area. Committing the transaction merely ensures that the updates caused by the statements are written to a durable store, from the temporary working area. This is often the case in most/all databases.

It is therefore safe to close a Statement object once you no longer need it, without encountering any side effects in the transaction.

like image 44
Vineet Reynolds Avatar answered Sep 25 '22 15:09

Vineet Reynolds