0

我在 PostgreSQL 数据库上使用 JDBC。当我在结果集中查询实体时,它返回 5 行。与该实体相关的是另一个实体,我在使用上述结果集中的一行时查询该实体。当我执行此查询时,上述结果集已关闭。

这意味着它一次只允许 1 个结果集在 1 个连接上处于活动状态。

以前,相同的代码非常适合 Oracle DB 服务器。

我是否需要让数据库管理员配置服务器以允许多个结果集?或者对代码做一些改变?或者在postgre中不可能做到这一点?以下是更多详细信息的代码:

    Connection conn = PTSConnection.getConnection();

    Statement stmt = conn.createStatement();

    ResultSet lines = stmt.executeQuery("SELECT LINEID,STARTSTOPID,ENDSTOPID FROM LINES"); **//first resultset is active**

    while (lines.next()){
        int lineId= lines.getInt(1);
        Stop ss = StopStorage.getByID(lines.getInt(2));
        Stop es = StopStorage.getByID(lines.getInt(3));
        ResultSet stops = stmt.executeQuery("SELECT STOPID FROM STOPSINLINES WHERE LINEID=" + lineId); **//first resultset dies**

        List<Stop> lineStops = new ArrayList<Stop>();
        while(stops.next()){
            Stop stop = StopStorage.getByID(stops.getInt(1));
            lineStops.add(stop);
        }
        stops.close();

        Line aLine = null;

        ResultSet emergencyLine = stmt.executeQuery("SELECT CAUSE, STARTTIME, ENDTIME FROM EMERGENCYLINES WHERE LINEID =" + lineId);
        if(emergencyLine.next()){
            String cause = emergencyLine.getString(1);
            Time startTime = emergencyLine.getTime(2);
            Time endTime = emergencyLine.getTime(3);

            aLine = new EmergencyLine(ss, es, cause, startTime, endTime, (Stop[]) lineStops.toArray(new Stop[lineStops.size()]));
        } else {
            aLine = new Line(ss, es, (Stop[]) lineStops.toArray(new Stop[lineStops.size()]));
        }

        emergencyLine.close();

        LineRepository.getInstance().addLine(aLine);
    }

    lines.close();
4

1 回答 1

0

原因不是您在同一连接上使用了两个结果集,而是您将同一Statement对象重新用于新查询。当您在 Statement 实例上运行 executeQuery() 时,任何先前的结果都将被关闭(我很惊讶您的代码确实适用于 Oracle ...)

只需在执行第二个查询之前创建一个新的 Statement 对象:

语句 stmt = conn.createStatement();
语句nestedStmt = conn.createStatement();

ResultSet lines = stmt.executeQuery("SELECT LINEID,STARTSTOPID,ENDSTOPID FROM LINES"); **//第一个结果集处于活动状态**

而(lines.next()){
  ...
    ResultSet stop = nestedStmt.executeQuery("SELECT STOPID FROM STOPSINLINES WHERE LINEID=" + lineId); **//第一个结果集死亡**
    列出 lineStops = new ArrayList();
    同时(停止。下一个()){
        停止停止 = StopStorage.getByID(stops.getInt(1));
        lineStops.add(停止);
    }
    停止。关闭();

    ...
    ResultSet EmergencyLine = nestedStmt.executeQuery("SELECT CAUSE, STARTTIME, ENDTIME FROM EMERGENCYLINES WHERE LINEID=" + lineId);
    如果(紧急线。下一个()){
        字符串原因 = EmergencyLine.getString(1);

    ……
    }
    紧急线.close();

并且不要 get 正确关闭所有Statements 和 ResultSets !

于 2011-01-09T10:54:13.613 回答