我在PostgreSQL数据库上使用JDBC。 当我在结果集中查询实体时,它返回5行。 与该实体相关的是另一个实体,当我在上面的结果集中使用一行时,我会查询该实体。 当我执行此查询时,上述结果集将被关闭。
这意味着它一次只能在1个连接上激活1个结果集。
以前,相同的代码适用于Oracle DB服务器。
是否需要请求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();
答案 0 :(得分:0)
原因不是您在同一连接上使用两个结果集,而是重新使用相同的Statement
对象进行新查询。当您在Statement实例上运行executeQuery()时,任何以前的结果都将被关闭(我很惊讶您的代码确实与Oracle一起工作...)
在执行第二个查询之前,只需创建一个新的Statement对象:
Statement stmt = conn.createStatement(); Statement nestedStmt = conn.createStatement(); ResultSet lines = stmt.executeQuery("SELECT LINEID,STARTSTOPID,ENDSTOPID FROM LINES"); **//first resultset is active** while (lines.next()){ ... ResultSet stops = nestedStmt.executeQuery("SELECT STOPID FROM STOPSINLINES WHERE LINEID=" + lineId); **//first resultset dies** List lineStops = new ArrayList(); while(stops.next()){ Stop stop = StopStorage.getByID(stops.getInt(1)); lineStops.add(stop); } stops.close(); ... ResultSet emergencyLine = nestedStmt.executeQuery("SELECT CAUSE, STARTTIME, ENDTIME FROM EMERGENCYLINES WHERE LINEID =" + lineId); if(emergencyLine.next()){ String cause = emergencyLine.getString(1); .... } emergencyLine.close();
并且不要正确关闭所有语句和结果集!