我从这段代码中得到标题中提到的错误,我不确定为什么...
public String[] getLobbies() {
String sql = "SELECT * FROM lobby";
SQLResponse<ResultSet> response = unclosedOperate(PreparedStatement::executeQuery, sql);
SQLResponse<ResultSet> countResponse = unclosedOperate(PreparedStatement::executeQuery, "SELECT COUNT(*) AS count FROM lobby");
if (!response.hasResponse() || !countResponse.hasResponse()) return new String[0];
try {
if (countResponse.getResponse().next()) {
int count = countResponse.getResponse().getInt("count");
String[] array = new String[count];
if (response.getResponse().next()) {
for (int i = 0; i < count; i++) {
Logger.debug("count: " + count);
Logger.debug("i: " + i);
array[i] = response.getResponse().getString(i + 1);
}
}
return array;
}
return new String[0];
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(response.getResponse());
close(countResponse.getResponse());
}
return new String[0];
}
它正在将此打印到控制台...
[07:14:57 ERROR]: count: 2
[07:14:57 ERROR]: i: 0
[07:14:57 ERROR]: count: 2
[07:14:57 ERROR]: i: 1
[07:14:57 WARN]: java.sql.SQLException: Column Index out of range, 2 > 1.
这不应该发生..? SQL 是一种索引,不是吗?列中有两个条目,我想检索这两个条目,但是当我检索第二个条目时它会抛出该错误,即使当我计算条目时它显示那里有 2 个... 哦,我的 table 现在看起来像这样...... https://gyazo.com/8af53da8b78b38a63864ae5a1a8f43e6
最佳答案
您遇到的问题是您没有遍历结果列表,而是尝试从响应访问结果集中的下一列。由于您的结果集仅返回一个列,因此您只能访问 getString(1)
(列偏移 1 而不是从 0 开始)。
不是调用 getResponse
然后循环,而是循环并为每一行调用 getResponse
,始终调用 getString(1)
(或作为一个更明确一点并使用实际的列名)。
if (countResponse.getResponse().next()) {
int count = countResponse.getResponse().getInt("count");
String[] array = new String[count];
Logger.debug("count: " + count);
for (int i = 0; i < count; i++) {
if (response.getResponse().next()) {
Logger.debug("i: " + i);
array[i] = response.getResponse().getString(1);
}
}
return array;
}
话虽如此,这可以大大简化。您不需要获取 count
来实例化数组。然后你可以只使用 while
循环响应并构建你的数组......
关于java.sql.SQLException : Column Index out of range, 2 > 1 即使我计算了列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53732816/