1

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.

2
  • my initial attempt at fixing it was based on this response here Commented May 22, 2020 at 19:33
  • What is data type of client_id ? You can use Object also for unknow type Commented May 22, 2020 at 19:41

1 Answer 1

2

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));
    }
Sign up to request clarification or add additional context in comments.

1 Comment

This is the same answer I came to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.