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
Release: 2024-12-27 12:12:09
Original
216 people have browsed it

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));

}
Copy after login

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);

}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template