Java 如果行不存在,如何停止尝试检索行?
经过调查,这似乎很常见,但我没有找到一个真正适合我所寻找的答案 我有一个返回前5行的方法。但是,当行为空时,会弹出 java.sql.SQLException:对空结果集的非法操作 每空一行 当没有更多的行时,如何阻止代码尝试返回结果Java 如果行不存在,如何停止尝试检索行?,java,mysql,sql,Java,Mysql,Sql,经过调查,这似乎很常见,但我没有找到一个真正适合我所寻找的答案 我有一个返回前5行的方法。但是,当行为空时,会弹出 java.sql.SQLException:对空结果集的非法操作 每空一行 当没有更多的行时,如何阻止代码尝试返回结果 public Appointment viewUpcomingAppointmentsDB(int i) throws SQLException { Connection myConn = DriverManager.getConnection(dBPat
public Appointment viewUpcomingAppointmentsDB(int i) throws SQLException {
Connection myConn = DriverManager.getConnection(dBPath, dBUsername, dbPassword);
Statement myStmt = myConn.createStatement();
Appointment ap1 = new Appointment();
ResultSet myRs = myStmt.executeQuery(
"select a.AppointmentID, a.Time, a.Date, d.SName, p.SName from Appointment as a" +
" Inner join Doctor as d on d.DoctorID = a.DoctorID Inner join Patient as p on " +
"p.PatientNInsurance = a.PatientNInsurance where Date(a.date) >= DATE(NOW()) order by Date");
int k = 0;
while (k < rowsToRead) {
myRs.next();
k++;
}
ap1.setAppointmentID(myRs.getString("AppointmentID"));
ap1.setDate(myRs.getString("Date"));
ap1.setTime(myRs.getString("Time"));
ap1.setPatientName(myRs.getString("p.SName"));
ap1.setDoctorName(myRs.getString("d.SName"));
myStmt.close();
myConn.close();
return ap1;
}
public Appointment viewUpComingAppointsDB(inti)抛出SQLException{
Connection myConn=DriverManager.getConnection(dBPath、dBUsername、dbPassword);
语句myStmt=myConn.createStatement();
预约ap1=新预约();
结果集myRs=myStmt.executeQuery(
从约会中选择a.AppointmentID、a.Time、a.Date、d.SName、p.SName作为+
“内部连接医生为d on d.DoctorID=a.DoctorID内部连接患者为p on”+
“p.PatientInsurance=a.PatientInsurance,其中Date(a.Date)>=Date(NOW())order by Date”);
int k=0;
while(k
提前感谢您的帮助
while (myRs.next() || k > i){
// do stuff with the current row
}
当resultSet中没有更多可用行或达到限制i时,该循环将停止
在本例中,当到达i参数时停止,该参数可能大于结果集中的实际行数
代码中还有其他问题,但这应该可以回答您的问题。您在循环中调用了两次next()
不要。
if (myRs.next()) { // <-- Advances to the next row
while (k < i) { // <-- What is this loop supposed to do?
}
myRs.next(); // <-- Advances to the next row, but that
// row is never used. Delete this line.
k++;
}
该循环将在
i
行之后退出,或者当ResultSet
耗尽所有可用行时退出,以先到者为准。谢谢!你介意详细说明一下其他问题吗?我真的很感激任何建议。看起来我(现在叫rowsToRead)是您想要的最大行,那么您应该将该限制添加到sql请求(“限制”+rowsToRead)。此外,我也不了解整个事情。你抓取一堆行,移动到一行(第i行),然后用它返回约会。这对性能非常不利。查看该方法的任何调用是否可以传递您想要获取的约会id,不要(尝试)在注释中发布代码。编辑你的问题。
for (int row = 1; row <= i && myRs.next(); row++) {
// process row here
}