Home >Database >Mysql Tutorial >Should I Close Pooled JDBC Connections?
Closing JDBC Connections in Pool
Question: Should JDBC connections be closed when using a connection pool? If so, doesn't it defeat the purpose of pooling?
Answer: Yes, pooled connections should be closed. Closing a pooled connection releases the underlying connection back to the pool.
The connection pool keeps track of which connections are in use and which are free. When a connection is closed, the pool recognizes it as available for reuse.
Question: Is the following method suitable for obtaining a connection from the pool or the DriverManager?
public Connection getConnection(boolean pooledConnection) throws SQLException { if (pooledConnection) { if (ds == null) { try { ds = (DataSource) new InitialContext().lookup("java:comp/env/jdbc/NamedInTomcat"); return ds.getConnection(); } catch (NamingException e) { e.printStackTrace(); } } return (ds == null) ? getConnection(false) : ds.getConnection(); } return DriverManager.getConnection("jdbc:mysql://..." + dbName, uName, pWord); }
Answer: The code is not recommended. The DataSource should be initialized once during application startup instead of in the method. Additionally, synchronization and null checks are unnecessary. The method should simply look up the DataSource once and return connections from it consistently.
Additional Considerations:
The above is the detailed content of Should I Close Pooled JDBC Connections?. For more information, please follow other related articles on the PHP Chinese website!