0

I have defined a variable with

Object[] data;

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

I want to do something like this:

    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());
Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181
  • A duplicate to http://stackoverflow.com/questions/8751735/java-retrieving-data-from-database-and-load-in-jtable — why post the same question twice? – alf Jan 08 '12 at 01:23
  • A duplicate to http://stackoverflow.com/questions/8775076/jtablejdbc-easiest-way apparently – alf Jan 08 '12 at 11:04

2 Answers2

4

It's

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

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

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.

Hope that helps.

alf
  • 8,377
  • 24
  • 45
  • Even if I just want to load the new data into a JTable? I don't want to operate with them in any way. – Evgenij Reznik Jan 08 '12 at 01:00
  • Maybe you can create an addRow method that directly selects and updates the JTable ? – Cemre Mengü Jan 08 '12 at 01:04
  • 1
    @kavuch especially if you just want to show the data in a JTable: look at custom `TableModel`s, aren't they shiny? Seriously, it depends. If you just need a 2D array, use `new Object[] {rs.getString("fname"), rs.getString("lname")};` reading elements, a `List` to hold those, and `return data.toArray(new Object[data.size()][]);` to get the resulting matrix. It is an awful approach, though, and I'd never recommend it. – alf Jan 08 '12 at 01:12
  • @Cemre what about encapsulation? You'll end up with a method that knows about both DB details and Swing internals—a nice mess indeed. – alf Jan 08 '12 at 01:13
  • You mean, I really should create a new class, only for loading my data into a JTable? Sorry, but I think it's too much work for such a small thing. No, I'm not lazy, I just don't think, it's really necessary. There are many tutorials using Vectors, for example, but I find them ugly... – Evgenij Reznik Jan 08 '12 at 01:50
  • @kavuch if all you have in your application is this table, then it's not too much work: it's only one class. If, on the other hand, you have a dozen of tables in your app, trying to find the ends will be a nightmare. Using data matrices only works if you don't care about the actual data meaning (e.g. Machine Learning: it's all "features") or if you're building a throw-away protottype. I think it's the latter case, so go on. – alf Jan 08 '12 at 10:48
  • @kavuch now regarding `Vector`s, it's a legacy code for you. No one likes them these days, but `DefaultTableModel` is all Vectors. – alf Jan 08 '12 at 11:04
  • @alf I see your point but I once read that objects should tell each other what they want to happen rather than querying each other for state and do the task themselves (i.e A tells B to update the table rather than query B to get the state and update the table itself). What is your opinion about this ? – Cemre Mengü Jan 08 '12 at 12:55
  • @Cemre that's a call for a long article. In brief, there's no "but," there's "and also..."—you're right, but you still need to separate the concerns. – alf Jan 08 '12 at 13:02
  • @alf: writing "data.add(new Customer(rs.getString("fname"), (rs.getString("lname")));" I receive: "array required, but java.util.List found". – Evgenij Reznik Jan 08 '12 at 21:24
  • @kavuch that's hard to believe. `new Customer(rs.getString("fname"), (s.getString("lname"))` creates a `Customer`, not a `java.util.List`. I guess your problem is in a different line. – alf Jan 08 '12 at 21:30
  • Sorry, but that is the truth: `Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - array required, but java.util.List found at callcenter.DB.select(DB.java:59)` – Evgenij Reznik Jan 08 '12 at 21:35
  • 1
    Very interesting exception. I believe you're using NetBeans, and the problem is described here: http://stackoverflow.com/questions/2333285/java-lang-runtimeexception-uncompilable-source-code-what-can-cause-this — as of the code, it seems you're mixing several approaches: what you store to the `List` must correspond the list's declared generic type. Unfortunately, comments are not a good fit for a discussion, so either create a new question outlining this very problem, or just check all the types: IDE should highlight the violations for you. – alf Jan 08 '12 at 22:03
0

I think its better to use an array list in this case (since your probably dont how much data that the "SELECT * FROM CUSTOMERS" query will return) and make use of its .add method instead of using a native array.

Try:

ArrayList<Object> myArray = new ArrayList<Object>(); 

while(...){
   myArray.add(anything that has type Object);
}
Cemre Mengü
  • 18,062
  • 27
  • 111
  • 169