如何正确保持连接打开?
您 一定不 要这样做,让连接池来处理。
在后台,连接池将保持与数据库引擎(MySQL,Oracle,SQL Server
…取决于您如何配置)的一系列数据库连接
SLEEPING。执行此代码时:
//avoiding all the particular exceptions just for pre simplicity purposes... //in real world applications, you must handle each of these exceptions public Connection getConnection() throws Exception { ctx = new InitialContext(); ds1 = (javax.sql.DataSource) ctx.lookup(strDSName1); return ds1.getConnection(); }您要求连接池检索这些可用连接之一。连接池将为您提供数据库连接(如果可用),并允许您随意使用它。然后,您可以在任何需要的地方使用它并 关闭它 :
public void foo() throws Exception { Connection connection = getConnection(); //do what you want/need... //in the end, you close the connection //this is A MUST! connection.close(); }connection.close()从连接池检索到的连接执行时,您不是在关闭物理数据库连接,而是通知连接池此特定的数据库连接必须返回到
SLEEPING状态。
来自解释的一些建议:
- 您 一定不要 尝试保持连接活动,这是连接池的工作。
- 您 一定不要 尝试将连接存储在任何类似于 缓存 的结构中,这就是连接池的工作。
- 您 必须
java.sql.Connection
在需要的最短范围内检索它。使用完后,将其 关闭 。



