Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 530
yrazlik Avatar asked Jul 09 '13 23:07

yrazlik


2 Answers

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

like image 197
Luiggi Mendoza Avatar answered Oct 17 '22 11:10

Luiggi Mendoza


Our object:

import java.io.Serializable;
...
class Account implements Serializable{
   public String data;
}

How to get our object from bd:

while (rs.next()) {
        Object accountJustObject = rs.getObject(i); 
        Account account = (Account)accountJustObject;
        accounts.add(account);
        i++;
} 

How to save our object:

public void InsertAccount(int id, Account newaccount){
 reparedStatement insertNew = conn.prepareStatement(
  "INSERT INTO root(id,account) VALUES (?,?)";
   insertNew.setInt(1, id);             //INT   field type
   insertNew.setObject(2, newaccount);  //OTHER field type
   insertNew.executeUpdate();  
 )
}

Tested under H2 database.

like image 45
Ilja Vost Avatar answered Oct 17 '22 12:10

Ilja Vost