Java - 连接关闭后无法使用ResultSet [英] Java - Can't use ResultSet after connection close

查看:677
本文介绍了Java - 连接关闭后无法使用ResultSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关闭与MySQL的连接时遇到问题。

I have a problem with closing a connection to MySQL.

我收到错误:


java.sql.SQLException:ResultSet关闭后不允许操作

java.sql.SQLException: Operation not allowed after ResultSet closed

我的代码:

public static ResultSet sqlquery (String query)
{
 ResultSet rs=null;
 Connection connection=null;
 Statement st=null;
 try{   
     Class.forName("com.mysql.jdbc.Driver");
     connection = DriverManager.getConnection("databaseadress","username","password");
     st = connection.createStatement();  
     rs = st.executeQuery(query);

    }catch(SQLException e){System.out.println("SQL error: " + e);}
      catch(Exception e){System.out.println("Error: " + e);}
       finally {
       try{
          if(rs != null) rs.close();
          if(st!= null) st.close();
          if(connection != null)  connection.close();
  }catch(SQLException e){System.out.println("SQL error : " + e);}

    }
     return rs;
}


推荐答案

这是JDBC的工作方式。在您的代码中,您关闭了 ResultSet Connection ,之后 ResultSet 不再可用。如果您希望它可用,则必须将其保留(并且连接)。

This is the way JDBC works. In your code you closed the ResultSet and the Connection, after which the ResultSet is no longer usable. If you want it to be usable you must leave it (and the Connection) open.

但是,如果你返回 ResultSet ,你应该重构你的代码,以便调用方法提供连接

However, if you return the ResultSet, you should refactor your code so the calling method provides the Connection.

这篇关于Java - 连接关闭后无法使用ResultSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆