Search code examples
javajdbcresultset

Resultset's getObject() method - how to use it properly?


I make a database query and store Account objects in the ResultSet. Here is the code:

try {
    ResultSet rs = queryDatabase();
    int i=0;
    while (rs.next()) {
        Account account= rs.getObject(i, Account); //ERROR
        accounts.add(account);
        i++;
    } 
} catch (Exception e) {
}

This code returns 3 objects and stores them in the rs. Then I want to get those objects in the ResultSet and put them into an ArrayList as you see in the code. But it gives an error in the specified line saying that ; expected. How can I use getObject method properly?


Solution

  • ResultSet.getObject (and the other getXxx methods) will retrieve the data from the current row of the ResultSet and starts in index 1. You have set your i variable with 0 value.

    Just change this

    int i=0;
    

    To

    int i=1;
    

    Also, getObject needs a single param, but you're incorrectly sending two:

    Account account= rs.getObject(i, Account);
    

    Probably you were trying to use ResultSet#getObject(int, Class) (available from Java 7), but you have to take into account that your Account class can't be magically converted from a database column to an instance of this object.

    Looks like it would be better to review JDBC trial first, then retry to solve your problem.

    Here's another good source to review: Using Customized Type Mappings