javamysqlswingresultsetapache-commons-dbutils

More than one jTable with the same ResultSet in Java


Can you populate more than one jTable with the same resultSet?

public void tableDisplay() {

    String tableQuery = "SELECT foodQuantity,foodName FROM food ORDER BY RAND() LIMIT 3";
    ResultSet rs;
    PreparedStatement statement;
    try {

        statement = con.prepareStatement(tableQuery);
        rs = statement.executeQuery();
        jTable1.setModel(DbUtils.resultSetToTableModel(rs));
        jTable2.setModel(DbUtils.resultSetToTableModel(rs));

    } catch (SQLException ex) {
        System.out.println(ex.toString());
    }
}

The code compiles but the second table doesn't get any records from DB. The point is that I need to select random items from mySql table and I want to display them in few jTables.


Solution

  • Without knowing too much about your code, I'd say that you need to call DbUtils.resultSetToTableModel(rs) once, and store the resulting table model in a local variable. Then, pass that local variable to the two setModel(...) methods