3

Suppose I have the following code

DataSource source = (DataSource) (new InitialContext()).lookup("jdbc/myName"); 
Connection connnection = source.getConnection() 

//use the connection to do some database operations...

at the end, should I still call

connection.close() to release the resource?

If the connection is from a connection pool, if I don't do anything, the connection should be automatically returned to the pool, right?

On the other hand, if I close it, is there gonna be any adverse effect on the connection pool (ie, after several calls, there won't be any connection left in the pool?)

Paul Sasik
  • 79,492
  • 20
  • 149
  • 189
neo
  • 2,461
  • 9
  • 42
  • 67

2 Answers2

3

The answer is yes, and check Closing JDBC Connections in Pool and JDBC Connection Pooling Best Practices for more information.

Community
  • 1
  • 1
Bastardo
  • 4,144
  • 9
  • 41
  • 60
1

Yes, you should be closing the connection, if only for quick recovery by the pool.

This article http://www.javaranch.com/journal/200601/JDBCConnectionPooling.html advises placement of a .close() call in a finally block.

David Hill
  • 4,102
  • 2
  • 23
  • 19