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());
It’s
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:
Now you may ask what’s
iand how do we create thedatain 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 usingListinstead:Note that you can almost read it aloud:
data, add a newCustomer, please.Finally, I highly recommend you to take a look at the
finallykeyword: it will save you time otherwise spent on strange and intermittent bugs.Hope that helps.