Home >Java >javaTutorial >How to Populate a JTable from a ResultSet in Java Without an IllegalStateException?

How to Populate a JTable from a ResultSet in Java Without an IllegalStateException?

Susan Sarandon
Susan SarandonOriginal
2024-12-27 12:12:09215browse

How to Populate a JTable from a ResultSet in Java Without an IllegalStateException?

Populating JTable from ResultSet

When attempting to populate a JTable from a ResultSet using your provided code, you may encounter the error "java.lang.IllegalStateException: SQLite JDBC: inconsistent internal state." To address this and simplify the process, consider employing a more straightforward method.

The following example demonstrates a way to construct a model from a ResultSet instance:

public static void main(String[] args) throws Exception {
    // Obtain the Connection
    
    ResultSet rs = stmt.executeQuery("select * from product_info");

    // Create and display the table
    JTable table = new JTable(buildTableModel(rs));

    // Close the Connection

    JOptionPane.showMessageDialog(null, new JScrollPane(table));

}

The "buildTableModel" method is defined as:

public static DefaultTableModel buildTableModel(ResultSet rs)
        throws SQLException {

    ResultSetMetaData metaData = rs.getMetaData();

    // Column names
    Vector<String> columnNames = new Vector<String>();
    int columnCount = metaData.getColumnCount();
    for (int column = 1; column <= columnCount; column++) {
        columnNames.add(metaData.getColumnName(column));
    }

    // Table data
    Vector<Vector<Object>> data = new Vector<Vector<Object>>();
    while (rs.next()) {
        Vector<Object> vector = new Vector<Object>();
        for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
            vector.add(rs.getObject(columnIndex));
        }
        data.add(vector);
    }

    return new DefaultTableModel(data, columnNames);

}

The above is the detailed content of How to Populate a JTable from a ResultSet in Java Without an IllegalStateException?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn