Tuesday, June 17, 2008

HSQLDB - Closing Database Connection

If you are using HSQLDB and you are getting exceptions like:

Could not get JDBC Connection; nested exception is java.sql.SQLException: The database is already in use by another process ...

or

java.lang.Exception: The process cannot access the file because another process has locked a portion of the file ...

then you probably need to close the database connection correctly.

Call the following method:
org.hsqldb.DatabaseManager.closeDatabases(0);

For example if you are using HSQLBD in your unit tests then it is necessary to call org.hsqldb.DatabaseManager.closeDatabases(0); in every tearDown() method in each unit test.

References:
[1] Unit Testing of Database Applications
[2] How to close all connections in HSQLDB

4 comments:

Lukáš Zapletal said...

Yes, it is good idea to close connections, files, resources... What a surprise ;-) Anyway thanks for the report, good to know this "error".

Lukas said...

As far as I understand the issue is that there is a regular way of closing the database connection (see http://hsqldb.org/doc/guide/ch01.html#N101DB) but this procedure does not suit unit tests because it can take some time for the database to really close (and release all files on the file system). If you need to close the database in a fast fashion (typically after each unit test) then the method described in the post can do the work for you.

Lukáš Zapletal said...

I am having different problem with different thing -- db4o. When I try to open a database I see exception DatabaseClosedException... Strange, I will be solving this in the evening at the hotel...

Lukas said...

Happy solving Lukas ... ;-)