Reputation: 37
I'm trying to get a table from my SQL database using a select distinct query and then putting it into an array. However, I am getting an error when I try to save the array as a variable.
Code:
private ResultSet query(String query) throws SQLException {
assert testConn();
try {
Statement statement = connection.createStatement();
return statement.executeQuery(query);
} catch (SQLException e) {
e.printStackTrace();
}
throw new SQLException();
}
private boolean testConn(){
try {
return connection.isValid(1);
} catch (SQLException e){
return false;
}
}
@Test
void test_rs(){
try {
ResultSet rs = query("select distinct client_id from email_filtering_scores;");
Array a = rs.getArray("client_id");
String[] set = (String[])a.getArray();
System.out.println(Arrays.deepToString(set));
} catch (SQLException e) {
e.printStackTrace();
}
}
I don't know why this is throwing the SQLException so any help is appreciated.
Thanks in advance.
PS. I don't know what best practice is for using jdbc so if there's anything that egregious with my code I would love some advice.
Upvotes: 1
Views: 204
Reputation: 4867
Just check if the resultset has values using next()
if (rs.next()) {
Array a = rs.getArray("client_id");
String[] set = (String[]) a.getArray();
System.out.println(Arrays.deepToString(set));
}
Upvotes: 2