Method resultset getObject () - how to use it correctly?

I make a database query and save the Account objects in a 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 rs. Then I want to get these objects in a ResultSet and put them in 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 getObject ?

+8
java jdbc resultset
source share
3 answers

ResultSet.getObject (and other getXxx methods) will retrieve data from the current ResultSet line and run at index 1. You set the i variable with 0 value.

Just change this

 int i=0; 

For

 int i=1; 

In addition, getObject requires one parameter, but you are sending two incorrectly:

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

You probably tried to use ResultSet#getObject(int, Class) (available in Java 7), but you should bear in mind that your Account class cannot be magically converted from a database column to an instance of this object.

It seems like it would be better to check out the JDBC trial first , then try again to solve your problem.

Here's another good source to review: Using custom type mappings

+3
source share

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(); ) } 

Checked in H2 database.

+1
source share

Object Variables:

  • only links to a space in memory.
  • any link uses memory (a little bit)
  • way to get any type of class from a single link with simple TypeCasting
0
source share

All Articles