且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JTable Swing检索数据

更新时间:2023-12-04 15:38:31

几年前,在我在技术学校期间,我写了一个小图书馆帮助解决了一些练习提出的问题,其中包括aa DatabaseTableModel

Two years ago, during my time in technical school, I wrote a little library help solve some of the problems proposed by the exercises, which included a a DatabaseTableModel.

类从 AbstractTableModel 这意味着您可以将其设置为 JTable 的数据源。

The class extends from AbstractTableModel, which means you can set it as the your JTable's data source.

以下是从 ResultSet

public final void constructModel(ResultSet rs) throws SQLException {
    ResultSetMetaData rsmd = rs.getMetaData();
    rs.last();
    rowCount = rs.getRow();
    int columnCount = rsmd.getColumnCount();
    // DatabaseColumn simply holds a name and a Class<?>.
    columns = new DatabaseColumn[columnCount];
    // This is the Object[][] array that you were talking about.
    // It holds all the data from the ResultSet.
    data = new Object[columnCount][rowCount];
    for (int i = 0; i < columnCount; ++i) {
        // Figure out the column name and type.
        int j = i + 1;
        String colName = rsmd.getColumnLabel(j);
        Class<?> colClass = String.class;
        try {
            colClass = Class.forName(rsmd.getColumnClassName(j));
        } catch (ClassNotFoundException ex) {
            colClass = String.class;
        }
        columns[i] = new DatabaseColumn(colName, colClass);
        // Get the data in the current column as an Object.
        rs.beforeFirst();
        for (int k = 0; rs.next(); ++k) {
            data[i][k] = rs.getObject(j);
        }
    }
    // Notify listeners about the changes so they can update themselves.
    fireTableStructureChanged();
}

这个类在学校使用时工作,生产代码。当我今天查看它,我开始看到问题。

The class worked when I used it in school, but it isn't exactly production code. When I look at it today, I start to see problems.

一个问题是它正在加载 $ c> ResultSet 进入内存。可能会很快丑陋。

One problem is that it is loading the entire contents of the ResultSet into memory. Could get ugly pretty quickly.

此外,算法不是完全最优的。它循环使用数据库游标,就像没有什么;如果先检索当前行中的所有对象并将它们分配到适当的列,然后移动到下一个 ,则假定

Also, the algorithm isn't exactly optimal. It loops around with the database cursor as if it was nothing; I suppose that it would be less costly for the database if it had retrieved all the objects in the current row first and assigned them to their appropriate columns before moving on to the next row.

但是,我认为这是一个很好的起点。

Nevertheless, I think it is a good enough starting point.