简体   繁体   English

结果集的getObject()方法-如何正确使用它?

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

I make a database query and store Account objects in the ResultSet . 我进行数据库查询并将Account对象存储在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. 此代码返回3个对象并将其存储在rs中。 Then I want to get those objects in the ResultSet and put them into an ArrayList as you see in the code. 然后,我想在ResultSet获取那些对象,并将它们放入ArrayList如代码中所示。 But it gives an error in the specified line saying that ; 但是它在指定的行中给出了一个错误; expected. 预期。 How can I use getObject method properly? 如何正确使用getObject方法?

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. ResultSet.getObject (和其他getXxx方法)将从ResultSet的当前行检索数据,并从索引1开始。您已将i变量设置为0值。

Just change this 只是改变这个

int i=0;

To

int i=1;

Also, getObject needs a single param, but you're incorrectly sending two: 另外, getObject需要一个参数,但是您错误地发送了两个参数:

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. 可能您正在尝试使用ResultSet#getObject(int, Class) (可从Java 7获得),但必须考虑到Account类无法从数据库列神奇地转换为该对象的实例。

Looks like it would be better to review JDBC trial first, then retry to solve your problem. 看起来最好先回顾一下JDBC试用版 ,然后重试解决您的问题。

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: 如何从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. 在H2数据库下测试。

Object Variables, are: 对象变量是:

  • only REFERENCES to a space in memory. 仅引用内存中的空间。
  • any REFERENCE uses memory (just a little bit) 任何参考都使用内存(仅一点点)
  • the way to get/use any object of a specific Type of Class from one reference is by simple Typecasting it. 从一个引用中获取/使用特定类型的任何对象的方法是通过简单的Typecasting。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM