2

Normally our framework classes hibernate will handle the opening and closIng of databse connection.

But due to some technical requirement, we are required to open another database connection using a direct call to the database through jndi.

For this case how do we thoroughly test that our open connection and close connection will work correctly as expected?

Beside putting conn.close in an exception finally block?

Malachi
  • 3,205
  • 4
  • 29
  • 46
Fffc
  • 21
  • 1
  • 2
  • Related question - http://stackoverflow.com/questions/274822/programmatically-checking-for-open-connection-in-jdbc and http://stackoverflow.com/questions/5075824/close-connection-to-db-does-not-close-all-connections – KV Prajapati Aug 27 '11 at 06:34

2 Answers2

3

It actually depends on the database. Most databases show the number of connections to them and can also display the ip address connecting to it. So, check in the database.

Otherwise, try running mock query after close and it should fail, catch the exception so it does not close the connection.

bknopper
  • 1,193
  • 12
  • 28
user669083
  • 151
  • 1
  • 5
  • +1, good thought about checking the DB for connections (although I don't know how you would do that programmatically - would be interesting to find out!). – Josh Darnell Aug 27 '11 at 06:11
  • Heh, just found out for [SQL Server](http://stackoverflow.com/questions/1248423/how-to-see-active-sql-server-connections) – Josh Darnell Aug 27 '11 at 06:34
2

Putting conn.close() in the finally seems good enough. I suppose after that, you could have another try-catch block where you attempt to execute a query against the database. If you get an exception, that will indicate (most likely) that your connection is closed completely.

Just a thought, hope that helps!

EDIT: Just to be clear, I mean doing something like this after you finally block (note that my Java syntax is a bit rusty, so this might not be exactly right, but you get the idea haha)

try
{
    s.executeQuery(sqlString);
}
catch(SQLException e)
{
    //examine error here to make sure it's because the connection is already closed
}
Josh Darnell
  • 11,304
  • 9
  • 38
  • 66