封闭连接:java中的下一个 [英] Closed Connection: next in java
问题描述
我有ResultSet方法,我正在关闭Connection中的一个块:
I have ResultSet Methods which I am closing the Connection in a finallly Block:
public static ResultSet countdrcountcr(String vforacid) throws SQLException {
ResultSet rs = null;
Connection conn = null;
try {
conn = db.getDbConnection();
String sql = "SELECT NVL (SUM (DECODE (part_tran_type, 'D', 1, 0)), 0), "
+ " NVL (SUM (DECODE (part_tran_type, 'C', 1, 0)), 0) "
+ " FROM tbaadm.htd WHERE acid IN (SELECT acid "
+ " FROM tbaadm.gam WHERE foracid = '" + vforacid + "') "
+ " AND tran_date >= '22-NOV-2013' AND tran_date <= '30-NOV-2013' "
+ " AND pstd_flg = 'Y' AND del_flg != 'Y'";
PreparedStatement ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
return rs;
} finally {
conn.close();
}
}
但我收到错误:
编辑整个ErrorTrace
Exception in thread "main" java.sql.SQLException: Closed Connection: next
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.OracleResultSetImpl.next(OracleResultSetImpl.java:181)
at statement.Statement.main(Statement.java:34)
Java Result: 1
我做得不对?
推荐答案
您将返回 ResultSet
以供将来使用,但在使用之后您将关闭连接,因此您无法由于资源已经关闭,因此检索数据。请注意,即使您在 try
或 catch <中返回某些内容,也始终会调用
finally
/ code>代码块,请参阅最终是否始终以Java执行?
You're returning a ResultSet
for future use but after using it you're closing the connection, so you have no way to retrieve the data since the resource is already closed. Note that finally
is always called, even if you return something in the try
or catch
code block, refer to Does finally always execute in Java?
详细地说,这就是问题所在:
In detail, this is the problem:
- 打开连接
- 准备陈述
- 获取结果集
- 返回结果集
- 关闭连接(即可以关闭相关资源,即它可以关闭与当前
相关联的
)因为,如之前的链接所示,PreparedStatement
和ResultSet
连接finally
块始终至少执行JVM崩溃或您使用System.exit
手动完成应用程序。 - 使用已关闭的
ResultSet
。它由于上一步而关闭。
- Open the connection
- Prepare a statement
- Get the result set
- Return the result set
- Close the connection (that may close the associated resources i.e. it may close the
PreparedStatement
and theResultSet
associated with the currentConnection
) because, as noted in the link before,finally
block is always executed at least that the JVM crashes or you manually finish the application usingSystem.exit
. - Using a closed
ResultSet
. It is closed due to the previous step.
一个可能的解决方案是你的 countdrcountcr
方法和返回 ResultSet
的所有其他方法接收 Connection
作为参数,因此调用它的方法将处理连接打开和关闭。另外,请注意,如果您在多线程环境中工作,则不应使用 static
方法来处理数据库操作,例如:一个Web应用程序。
A possible solution would be that your countdrcountcr
method and all other methods that return a ResultSet
receive the Connection
as parameter, so the method that calls it will handle the connection opening and closing. Also, take note that you should not use static
methods to handle your database operations if you're working in a multi threaded environment e.g. a web application.
这篇关于封闭连接:java中的下一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!