Search code examples
javaswingjdbcresultset

Updatable ResultSet row count


I want to bind a database table to a swing JTable, and make that JTable editable by using APIs in a updatable ResultSet(#insertRow,#deleteRow(),#updateRow()).

so I need to create a TableModel implementation by wrapping a ResultSet.

public class MyTableModel implements TableModel {

private ResultSet rs;

private ResultSetMetaData rsmd;

@Override
public int getRowCount() {
    return 0;
}

@Override
public int getColumnCount() {
    return 0;
}

@Override
public String getColumnName(int columnIndex) {
    return null;
}

@Override
public Class<?> getColumnClass(int columnIndex) {
    return null;
}

@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
    return false;
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    return null;
}

@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {

}

@Override
public void addTableModelListener(TableModelListener l) {

}

@Override
public void removeTableModelListener(TableModelListener l) {

}

}

then, how Can I implement the getRowCount() method ?

how to determine the numbers of rows in a updatable result set ?

for example, if user click a button "add row", then I call such methods :

        rs.moveToInsertRow();
        rs.updateString(1, "yqwang");
        rs.insertRow();

how to sync the JTable UI and the underlying ResultSet?


Solution

  • You should not do that. A ResultSet needs an open connection to the database, and the changes done to the result set won't be committed to the database until you commit the connection.

    This means that if the database decides to close the connection because it hasn't seen any activity for some time, or if your app crashes after three hours, you'll lose all the modifications done during these 3 hours.

    This also means that you might lock some rows for a whole lot of time, and thus make other transactions wait for a whole lot of time before being able to do anything.

    Copy the data from the result set into your table model, and start a new transaction each time you need to insert or update a row.