gpt4 book ai didi

java - 关闭池中的 JDBC 连接

转载 作者:IT老高 更新时间:2023-10-28 11:26:52 24 4
gpt4 key购买 nike

我们使用 JDBC 的标准代码部分是……

Connection conn = getConnection(...);
Statement stmt = conn.conn.createStatement (ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rset = stmt.executeQuery (sqlQuery);

// do stuff with rset

rset.close(); stmt.close(); conn.close();

问题一:在使用Connection Pool的时候,应该在最后关闭Connection吗?如果是这样,是不是失去了汇集的目的?如果没有,DataSource 如何知道某个特定的 Connection 实例何时被释放并可以重用?我对此有点困惑,任何指针表示赞赏。

问题 2: 以下方法是否接近标准?看起来像是试图从池中获取连接,如果无法建立 DataSource,请使用老式的 DriverManager。我们甚至不确定哪个部分在运行时被执行。重复上面的问题,是否应该关闭这种方法产生的连接?

synchronized public Connection getConnection (boolean pooledConnection)
throws SQLException {
if (pooledConnection) {
if (ds == null) {
try {
Context envCtx = (Context)
new InitialContext().lookup("java:comp/env");
ds = (DataSource) envCtx.lookup("jdbc/NamedInTomcat");
return ds.getConnection();
} catch (NamingException e) {
e.printStackTrace();
}}
return (ds == null) ? getConnection (false) : ds.getConnection();
}
return DriverManager.getConnection(
"jdbc:mysql://"+ipaddy+":"+dbPort +"/" + dbName, uName, pWord);
}

编辑:我认为我们正在获得池连接,因为我们没有看到堆栈跟踪。

最佳答案

When using Connection Pool, should one close the Connection at the end? If so, isn't the purpose of pooling lost? And if not, how does the DataSource know when a particular instance of Connection is freed up and can be reused? I am a little confused on this one, any pointers appreciated.

是的,当然您还需要关闭池连接。它实际上是实际连接的包装器。它将在幕后释放实际连接回池。进一步由池来决定实际连接是实际上 被关闭还是被重新用于新的 getConnection() 调用。所以,无论你是否使用连接池,你都应该alwaystry的finally block 中以相反的顺序关闭所有的JDBC资源 block 在您获得它们的位置。在 Java 7 中,这可以通过使用 try-with-resources 进一步简化。声明。


Is the following method anything close to standard? Looks like an attempt to get a connection from the pool, and if DataSource cannot be established, use the old fashioned DriverManager. We are not even sure which part is getting executed at runtime. Repeating the question above, should one close the Connection coming out of such a method?

这个例子很吓人。您只需要在应用程序启动期间在应用程序范围的数据库配置类的某些构造函数/初始化中查找/初始化一次 DataSource 。然后,在应用程序的剩余生命周期中,只需在同一个数据源上调用 getConnection()。不需要同步也不需要空检查。

另见:

关于java - 关闭池中的 JDBC 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4938517/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com