Reading a Access file using Jackcess and creating a Jtable with the data

1.7k views Asked by At

I'm currently working on a Java application that reads an Access file and builds a Jtable model using the data that's collected. I've previously done the same with an Excel file but when I tried with Jackcess it was slightly diffrent and I've ran into some questionmarks.

My work so far:

public class AccessModel{

public DefaultTableModel getAccessModel() throws IOException {
    Database db = DatabaseBuilder.open(new File("MyFile.accdb"));

    Vector<String> columnNames = new Vector<String>();
    Vector<String> vector = new Vector<String>();
    Vector<Vector<String>> data = new Vector<Vector<String>>();

    StringBuilder output = new StringBuilder();

            Table table = db.getTable("Table1");

    for (Column column : table.getColumns()) { // get the table column names
        output.append(column.getName());
        output.append("\n");
        columnNames.add(column.getName());
    }
    for (Column column : table.getColumns()) { // get the column rows and values
        vector.add(column.getRowValue(table.getNextRow()).toString());
    }
    data.add(vector);

    // return the model to Gui
    DefaultTableModel accessModel = new DefaultTableModel(data, columnNames);
    return accessModel;
    }
}

As you can see this method will only iterate trough the first row, then exit the loop. I'm either blind to an abvious solution due to 12 hours of straight work, or I'm doing something terribly wrong.

I've stumbled across some half-good solutions where an Iterator is used, but I cannot get the hang of it. Any suggestions on this? Or should I stay on lane with my current line of thought?

1

There are 1 answers

3
mKorbel On BEST ANSWER
  • JTable (value for view is stored in XxxTableModel, in your case is used DefaultTableModel) is row bases Object,

  • TableColumn (value is stored in TableColumnModel) to divide row(s) to the columns

  • you would need to create two Objects,

    1. Vector<String> columnNames (is only one row) for columns identifiers from Table table = db.getTable("Table1");
    2. loop inside Table table = db.getTable("Table1"); to fill two dimensional Vector<Vector<Object>> data = new Vector<Vector<Object>>(); by using Vector<Object> vector = new Vector<Object>();, notice 1st. code line insode loop must be vector = new Vector<Object>();, you have to create a new Vector otherwise you'll add the same rown_times, last code line should be data.add(vector)

.