Java,MySQL - 线程“main”中的异常java.sql.SQLException:ResultSet关闭后不允许操作

时间:2016-11-16 18:57:30

标签: java mysql jdbc resultset

我正在尝试获取ResultSet的第一个元素。为什么我收到此错误

public ResultSet executeSearch(String q){
        openConnection();
        ResultSet resultSet = null;
        try{
            Statement statement = connection.createStatement();
            resultSet = statement.executeQuery(q);
            closeConnection();
            return resultSet;
        }
        catch (Exception e){
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
        finally {
            closeConnection();
        }
        return resultSet;
    }

 public int getAddressID(String city) throws SQLException{
    String q = "SELECT PK_ADDRESS_ID FROM tbl_addresses WHERE city =" + "\'"+ city + "\';";
    System.out.println(q);
    ResultSet rs = executeSearch(q);
    int i = 0;
    if (rs.next()){
        i = rs.getInt(1);
    };
    return i;
}

1 个答案:

答案 0 :(得分:1)

您收到此错误是因为您尝试在关闭之后阅读ResultSet ,这是被禁止的。

您需要在方法ResultSet中关闭您的连接(以及getAddressID},而不是下一个:

public ResultSet executeSearch(String q){
    openConnection();
    try {
        return connection.createStatement().executeQuery(q);
    } catch (Exception e){
        JOptionPane.showMessageDialog(null, e.getMessage());
    }
    return null;
}

public int getAddressID(String city) throws SQLException{
    ...
    try (ResultSet rs = executeSearch(q)) {
        ...
    } finally {
         closeConnection();
    }
    return i;
}