填充对象[]数据 [英] Filling Object[] data

查看:103
本文介绍了填充对象[]数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经定义了一个变量

Object[] data;

如何在下一步填写数据?

How can I fill it up with data in the next step?

我想做这样的事情:

    public Object[] select() {
   Object[] data; // Here I definded it
    try {
        stmt = conn.createStatement();
        rs = stmt.executeQuery("SELECT * FROM CUSTOMERS");
        while (rs.next()) {

/* data = {(rs.getString("fname"), (rs.getString("lname")); */
// I know it's wrong, but how can I fill it with data from a database?

        }
        rs.close();
        stmt.close();
    } catch (SQLException ex) {
        System.out.println("error while selecting");
        System.err.println(ex);
    }
    return data;
}


// -----
// somewhere else
model.addRow(DB.INSTANCE.select());


推荐答案

这是

 data[i++] = new Object[] {rs.getString("fname"), rs.getString("lname")}; 

但坦率地说,我会考虑创建一个新类的选项。我甚至有一个奇特的名字:客户

But frankly I'd look at the option of creating a new class. I even have a fancy name for it: Customer.

这样你的主周期就是这样:

So that your main cycle would look like that:

 while (rs.next()) {
     data[i++] = new Customer(rs.getString("fname"), s.getString("lname"));
 }

现在你可以问什么是以及我们如何首先创建数据?所有好问题。您事先不知道结果集的长度,因此数组不是一个好主意。请尝试使用列表

Now you may ask what's i and how do we create the data in the first place? All good questions. You don't know beforehand how long the result set is going to be, so arrays are not a good idea. Try using List instead:

public List<Customer> select() {
    List<Customer> data = new ArrayList<Customer>(); // Here you define it
    // some code
        while (rs.next()) {
            data.add(new Customer(rs.getString("fname"), (s.getString("lname")));
        }
    // etc.
    return data;
}

请注意,您几乎可以大声朗读: data ,添加新的客户,拜托。

Note that you can almost read it aloud: data, add a new Customer, please.

最后,我强烈建议您查看 finally 关键字:它会节省你花在奇怪和间歇性错误上的时间。

Finally, I highly recommend you to take a look at the finally keyword: it will save you time otherwise spent on strange and intermittent bugs.

希望有所帮助。

这篇关于填充对象[]数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆