Reputation: 207
I am getting the error mentioned in the title from this code and Im not sure why...
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];
}
It's printing this to console...
[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.
This shouldn't be happening..? SQL is one indexed is it not? There are two entries in the column, I want to retrieve both of those entries, but when I retrieve the second entry it throws that error, even though when I count the entries it shows there being 2 in there... Oh, and my table currently looks like this... https://gyazo.com/8af53da8b78b38a63864ae5a1a8f43e6
Upvotes: 3
Views: 1330
Reputation: 62861
The problem you are having is you aren't iterating through the result list, but instead trying to access the next column in the resultset from the response. Since you're resultset only returns a single column, you can only access getString(1)
(columns are offset by 1 instead of starting at 0).
Instead of calling getResponse
and then looping, loop and call getResponse
for each row, always calling getString(1)
(or being a little more explicit and using the actual column name).
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;
}
With that said, this could be greatly simplified. You don't need to get the count
to instantiate the array. And then you could just use while
to loop through the responses and build your array...
Upvotes: 1