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

查看:32
本文介绍了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 的工作方式.在您的代码中,您关闭了 ResultSetConnection,之后 ResultSet 不再可用.如果您希望它可用,则必须将其(和 Connection)保持打开状态.

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,您应该重构您的代码,以便调用方法提供Connection.

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

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

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