在调查之后,这似乎很常见,但我没有找到一个真正适合我所寻找的答案。
我有这个方法会返回前5行。但是,当行为空时,会弹出
java.sql.SQLException:对空结果集的非法操作。
每个空行。
如果没有更多行,我将如何阻止此代码尝试返回结果?
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;
}
提前感谢您的帮助!
答案 0 :(得分:1)
while (myRs.next() || k > i){
// do stuff with the current row
}
当resultSet中没有可用的行或者你达到了极限时,该循环将停止。
在您的情况下,当您到达i参数时停止,该参数可能会大于结果集中的实际行数。
您的代码中还有其他问题但应该回答您的问题。
答案 1 :(得分:0)
你在循环中调用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
(错误名称,使用rowsToRead
或类似名称),请使用合并的for
循环:
for (int row = 1; row <= i && myRs.next(); row++) {
// process row here
}
该循环将在i
行之后退出,或者当ResultSet
耗尽所有可用行时,以先到者为准。