Populating JTable from ResultSet
The provided code snippet aims to populate a JTable with data retrieved from a database using ResultSet. However, it encounters the following error:
java.lang.IllegalStateException: SQLite JDBC: inconsistent internal state
Let's explore an alternative approach to resolve this issue and demonstrate how to effectively create a DefaultTableModel from ResultSet.
Creating a Model from ResultSet
The following code builds a DefaultTableModel from a ResultSet using the buildTableModel method:
import java.sql.ResultSet; import java.sql.SQLException; import java.util.Vector; public class ResultSetTableModel { public static DefaultTableModel buildTableModel(ResultSet rs) throws SQLException { ResultSetMetaData metaData = rs.getMetaData(); // Column names Vector<String> columnNames = new Vector<>(); int columnCount = metaData.getColumnCount(); for (int column = 1; column <= columnCount; column++) { columnNames.add(metaData.getColumnName(column)); } // Table data Vector<Vector<Object>> data = new Vector<>(); while (rs.next()) { Vector<Object> vector = new Vector<>(); for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) { vector.add(rs.getObject(columnIndex)); } data.add(vector); } return new DefaultTableModel(data, columnNames); } }
This method extracts column names and data from the ResultSet and returns a DefaultTableModel, which can then be assigned to a JTable.
Updating the Code
To use this method, update the getnPrintAllData method in your code as follows:
public void getnPrintAllData(){ String name, supplier, id; // ... try{ res = statement.executeQuery(); testResultSet(res); DefaultTableModel dtm = ResultSetTableModel.buildTableModel(res); gui.jTable1.setModel(dtm); // ... } catch(Exception e){ // ... } }
This should resolve the error and allow you to successfully populate the JTable with data from the ResultSet.
The above is the detailed content of How to Populate a JTable from a ResultSet in Java and Avoid `java.lang.IllegalStateException`?. For more information, please follow other related articles on the PHP Chinese website!