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!