Zyrax
Zyrax

Reputation: 171

Java JTable Displaying database records

I have problems fetching the database records, what is the best way to get the database records display in the JTable, so right now I used the resultset for fetching records and store it in the Object[][] array, I wanted this variable lets say Object[][] data its value to be displayed on JTable, I donn't know if I'm doing this right. And how can I initialize my Object[][] data size depending on the records inside my database. thanks

Here are my code:

ResultSet rs = null;
Statement sql = null;
Object[][] data = new Object[100][100];

        String query = "SELECT * FROM INVENTORY";
        sql = con.createStatement();
        sql.executeQuery(query);
        rs = sql.getResultSet();

        while(rs.next()){
            for(int i = 0; i < data.length; i++){
                for(int j = 0; j < data[i].length; j++){
                    int valId = rs.getInt(1);
                    String valName = rs.getString(2);
                    String valCat = rs.getString(3);
                    String valDesc = rs.getString(4);
                    double  valPrice = rs.getDouble(5);
                    int valstock = rs.getInt(6);
                    int valSupply = rs.getInt(7);

                    System.out.println(valId);
                    System.out.println(valName);
                    System.out.println(valCat);
                    System.out.println(valDesc);
                    System.out.println(valPrice);
                    System.out.println(valstock);
                    System.out.println(valSupply);

well as you can see I use multiple for loops for fetching the records, Is it right to use multiple for loops? or is there any easy way and how can I initialize my Object[][] array depending to the total records on my database?

Upvotes: 0

Views: 6991

Answers (4)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

Using Vectors from java.util.collection will solve your problem.....

See this nice example :

http://chang.advits.com/populate-data-from-database-into-jtable-in-netbeans

Upvotes: 1

MadProgrammer
MadProgrammer

Reputation: 347184

As I started in my previous answer.

You probably won't know how many rows are coming from the database in advance. There are techniques you can use, but they are only guesses at best (mind you, it's been a while since I played with JDBC).

Without knowing upfront the number of rows, you need some kind dynamic array. Funny enough, Java provides one. It's called ArrayList. This allows you to add elements to it without knowing how many elements you actually need.

Secondly, I'd store you row results in an Object that best represents that object, this will greatly reduce the complexity of the data structure and make it easier to adopt changes into the code, cause how long will column x be the value you're expecting...

Something like

public class Inventory {

    private int id;
    private String name;
    private String catagory;
    private String description;
    private double  price;
    private int stock;
    private int supply;

    public Inventory(int id, String name, String catagory, String description, double price, int stock, int supply) {
        this.id = id;
        this.name = name;
        this.catagory = catagory;
        this.description = description;
        this.price = price;
        this.stock = stock;
        this.supply = supply;
    }

    public void setCatagory(String catagory) {
        this.catagory = catagory;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public void setStock(int stock) {
        this.stock = stock;
    }

    public void setSupply(int supply) {
        this.supply = supply;
    }

    public String getCatagory() {
        return catagory;
    }

    public String getDescription() {
        return description;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }

    public int getStock() {
        return stock;
    }

    public int getSupply() {
        return supply;
    }

}

For example.

The I'd store this information into a List

List<Inventory> inventoryList = new ArrayList<Inventory>(50); // This is a "seed" value to helps performance
while(rs.next()){
    Inventory inventory = new Inventory(rs.getInt(1),
        rs.getString(2),
        rs.getString(3),
        rs.getString(4),
        rs.getDouble(5),
        rs.getInt(6),
        rs.getInt(7))
    inventoryList.add(inventory);
}

Basically from there, I'd be tempted to simply use the list. This means you will probably need to implement our own AbstractTableModel, but it will be far more useful to you in the long run

Upvotes: 2

David B
David B

Reputation: 3571

Make sure you initialize the size of data with the approriate row and column counts. To get the row count you may follow the procedure set here. And to get the column count, the answer is found on the JavaDocs.

In this way you remove one of the loops you have above. Leaving you only with

final int columnCount = rs.getMetaData().getColumnCount();
int row = 0;
while(rs.next()) {
   for(int index = 0; index < columnCount; index ++) {
      data[row][index] = rs.getObject(index);
   }
   row ++;
}

Or instead of using Object[][], use List<Model> wherein the Model follows the MVC architecture.

Upvotes: 1

norbitheeviljester
norbitheeviljester

Reputation: 962

you should use an ArrayList

First you create the data holder:

ArrayList<Object[]> data = new ArrayList<Object[]>();

Then you iterate over the resultSet row by row and create a new Object[] array each time you want to save the row. The number of items in the table should be the number of columns in your row:

while(rs.next()){
    Object[] row = new Object[]{rs.getInt(1), 
                    rs.getString(2), 
                    rs.getString(3), 
                    rs.getString(4),
                    rs.getDouble(5),
                    rs.getInt(6),
                    rs.getInt(7)};
    data.add(row);
}
Object[][] realData = data.toArray(new Object[data.size()][]);

It would also be great if you changed the SQL query to not use the '*' and just list the fields.

Upvotes: 2

Related Questions