Closing statement after database operation?

2019-08-04 19:11发布

问题:

Statement statement; Connection connection;

I am closing connection after every database operation as below.

connection.close();

i created statement object as below.

connection.createStatement(....)

Do i need to close satement also similar to connection closing?

I mean do i need to call statement.close();?

What will happen if it is not called?

Thanks!

回答1:

The Javadoc says it all:

Statement.close()

Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed. It is generally good practice to release resources as soon as you are finished with them to avoid tying up database resources.

One good way to ensure that close() is always called is by placing it inside a finally block:

Statement stmt = connection.createStatement();
try {
    // use `stmt'
} finally {
    stmt.close();
}

In Java 7, the above can be more concisely written as:

try (Statement stmt = connection.createStatement()) {
    // ...
}

This is called the try-with-resources statement.



回答2:

In general if you close a connection, all associated resources will be closed as well, provided the driver implementer did his work correctly. That said: it is better to close resources when your done with them, as that will free up resources both on your side and the database.



标签: java jdbc