我想将从数据库检索到的数据添加到数组中,但其检索数据为空。我的错是什么?请帮帮我。
for (User u : userLists) {
for (Resource r : resourceLists) {
String ratingQuery
= "SELECT rank FROM ratings WHERE userindex='"
+ u.getIndex()
+ "' AND resourceindex='"
+ r.getIndex()
+ "'";
try {
ratingCon = ConnectionManager.getConnection();
stmt = ratingCon.prepareStatement(ratingQuery);
rs = stmt.executeQuery();
while (rs.next()) {
rate = rs.getDouble("rank");
ratings[u.getIndex()][r.getIndex()] = rate; //it seems here is the problem
}
} catch (Exception e) {
System.out.println("Log In failed: An Exception has occurred! " + e);
}
}
}
最佳答案
如果ratings
是一个二维双精度数组,则这一行没有问题:
ratings[u.getIndex()][r.getIndex()] = rate;
但可能是您的数据库返回空的
ResultSet
?插入要调试的打印语句: while (rs.next()) {
rate = rs.getDouble("rank");
System.out.println("Result set is not empty! Current rank is: " + rate);
ratings[u.getIndex()][r.getIndex()] = rate; //it seems here is the problem
}
如果它什么也不打印-那么问题不在代码中而是在数据库数据中。另外,我认为您在查询结束时遗漏了分号
;
。关于异常处理:
catch (Exception e) {
System.out.println("Log In failed: An Exception has occurred! " + e);
}
您在这里捕获的异常类型太抽象-您不知道它是
SQLException
异常还是ArrayIndexOutOfBoundsException
。换成几个挡块。