java.sql.SQLException:即使我对列进行计数,列索引也超出范围,> 2> 1

时间:2018-12-11 21:48:42

标签: java mysql sql

我从这段代码中得到标题中提到的错误,我不确定为什么...

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个... 哦,我的桌子目前看起来像这样... https://gyazo.com/8af53da8b78b38a63864ae5a1a8f43e6

1 个答案:

答案 0 :(得分:1)

您遇到的问题是您没有遍历结果列表,而是尝试从响应中访问结果集中的下一列。由于结果集仅返回单列,因此只能访问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遍历响应并构建数组...

相关问题