在 JDBC 處理 ResultSet 時,若在循環中未正確推進游標或錯誤嵌套循環,會導致數組除首元素外全為默認值(0/null),進而引發後續計算錯誤。
// 讀取 rs2
for (int i = 0; i < numbercanshu; i++) {
while (rs2.next()) { // 游標推進到末尾
list2[i] = rs2.getInt("教師等級"); // i 不變,反覆覆寫 list2[0]
list4[i] = rs2.getInt("教學崗位標准");
}
} // 循環結束時,rs2 游標已在 afterLast,只有 list2[0] 有值
// 讀取 rs
for (int n = 0; n < number; n++) {
list3[n] = rs.getInt("級別");
break; // 直接跳出,只有 list3[0] 有值
}
// 後續雙層循環遍歷 list2、list3,實際僅比較 [0] 元素
while(rs.next()) 應在外層驅動行遍歷,內部按列賦值;現代碼導致單行數據反覆寫入同一索引。break:第二個循環首次迭代即中斷,僅讀取第一行。while 耗盡 rs2,後續無法重複讀取(除非 TYPE_SCROLL_INSENSITIVE)。// 假設 numbercanshu 為預期行數,實際以 ResultSet 為準
int i = 0;
while (rs2.next() && i < numbercanshu) {
list2[i] = rs2.getInt("教師等級");
list4[i] = rs2.getInt("教學崗位標准");
i++;
}
int actualCount2 = i; // 實際讀取行數
int n = 0;
while (rs.next() && n < number) {
list3[n] = rs.getInt("級別");
n++;
}
int actualCount3 = n;
// 計算時使用實際計數
for (int x = 0; x < actualCount2; x++) {
for (int y = 0; y < actualCount3; y++) {
if (list2[x] == list3[y]) {
money[y] += list4[x];
}
}
}
List<Integer> 替代固定長度數組,動態擴容避免越界與空值。try-with-resources 確保 Connection/Statement/ResultSet 正確關閉。ResultSet.TYPE_SCROLL_INSENSITIVE,或將數據先載入集合。rs.getRow()、list.size() 確認讀取行數。