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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With