gpt4 book ai didi

java - 连接行为 - DriverManager.getConnection() 和 DataSource.getConnection()

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:15:23 27 4
gpt4 key购买 nike

如果我使用 DriverManager.getConnection()DataSource.getConnection() 获取连接对象,当 .close() 是在那些对象上调用的?

.close() 方法调用之前,我从这两个不同的连接中获得了相关的 StatementResultSet 对象。在获得这两个对象后不久,如果我说 connection1.close()(通过 DriverManager.getConnection()),它将使连接对象无效,我不应该/允许访问相关的 Statement 和 ResultSet 对象。如果我错了,请纠正我?

第二种情况,现在如果我说 connection2.close()(通过 DataSource.getConnection()),它只是将它返回到池中。但连接仍然存在。我能否访问关联的 StatementResultSet 对象?

最佳答案

如果我们假设一个(基本的)DataSource(即:一个不进行连接池的),那么您获得的物理连接与从 DriverManager< 获得的物理连接相同(一些驱动程序甚至在内部使用来自 DataSource 的 DriverManager,或来自 DriverManager 的 DataSource)。因此这些连接的行为将相同。

现在,如果我们假设一个提供连接池的 DataSource,那么 DataSource 本身使用一个 ConnectionPoolDataSource(或类似的内部机制)来获得一个 PooledConnection。此 PooledConnection 管理与数据库的实际物理连接。

当用户从 DataSource 请求连接时,DataSource 将 checkout PooledConnection,并向其请求 Connection。然后 PooledConnection 将创建一个使用或包装物理连接的逻辑连接(例如使用代理)。 DataSource 会将逻辑连接返回给用户。

对于用户而言,逻辑连接在所有方面的行为都应与物理连接相同。因此,当用户关闭连接时,该逻辑连接和所有依赖的 JDBC 对象都将关闭,其行为与物理连接关闭相同。

JDBC 4.1 第 11.1 节说:

Connection pooling is completely transparent to the client: A client obtains a pooled connection and uses it just the same way it obtains and uses a non pooled connection.

和第 11.4 节:

If the application attempts to reuse the logical handle, the Connection implementation throws an SQLException.

For a given PooledConnection object, only the most recently produced logical Connection object will be valid. Any previously existing Connection object is automatically closed when the associated PooledConnection.getConnection method is called.

然而,在后台,当逻辑连接关闭时,PooledConnection 将向 DataSource 发出信号,表明它可以重用,然后 DataSource 会将其返回到连接池,或者关闭 PooledConnection(关闭物理连接) 如果它不再需要连接。

DataSource 还可以通过要求 PooledConnection 关闭逻辑连接来强制撤销来自用户的连接(例如,当连接 check out 时间过长时等)。

关于java - 连接行为 - DriverManager.getConnection() 和 DataSource.getConnection(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12541005/

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