java中下一个,封闭连接:java中的下一个

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();

}

}

But I am getting the error :

edit The whole 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

What am I not doing right?

解决方案

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:

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 the ResultSet associated with the current Connection) because, as noted in the link before, finally block is always executed at least that the JVM crashes or you manually finish the application using System.exit.

Using a closed ResultSet. It is closed due to the previous step.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值