简体   繁体   中英

Do I have to explicitly disconnect from a database when using Java?

It is necessary to disconnect from the database after the job is done in Java? If it is not disconnected, will it lead to memory leaks?

You must always close all your Connections, Statements and ResultSets.

If not, is more probable you can't obtain new connections from the pool than a memory leak.

You should provide more details like which framework you are using or something.

Anyway, are you using JDBC? If so you should close the following objects by using their respective close() methods: Statement, ResultSet and Connection.

Assuming you are using JDBC, the answer is yes. If you don't close the connection, then the JDBC driver might try to close it in a finallizer, but that could hold the connection open for a very long time, causing resource issues (the amount of database connections allowed to be open at one time is finite). Typically JDBC programming is done with a database pool, and not closing the connection will mean that the pool will run out of available connections very quickly.

Some application servers (eg JBoss) will detect when a connection wasn't closed and close it for you if it is managing the transactions, but you should not rely on that.

Of course some JDBC drivers are not pure java drivers, at which point memory leaks become a very real possibility.

I don't have a source, but I believe (if I remember right, it's been a while since I've touched JDBC) that it depends on the JDBC driver implementation. You should always close your connections and clean up after yourself as not all JDBC drivers do it for you (although some might).

This goes back to a rule that I like to follow - If I create or open something, I'm responsible for deleting or closing it.

是的,是的

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM