从ResultSet填充JTable的最简单代码我搜索了一整天却没有运气。我打电话getnPrintAllData()方法在按“确定”按钮后。所以代码是:public class DatabaseSQLiteConnection {
Connection conn = null;
PreparedStatement statement = null;
ResultSet res = null;
public DatabaseSQLiteConnection(){
try{
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:test.sqlite");
statement = conn.prepareStatement("SELECT * from product_info;");
}
catch(Exception e){
e.printStackTrace();
}
}
public void getnPrintAllData(){
String name, supplier, id;
DefaultTableModel dtm = new DefaultTableModel();
Window gui = new Window(); //My JPanel class
try{
res = statement.executeQuery();
testResultSet(res);
ResultSetMetaData meta = res.getMetaData();
int numberOfColumns = meta.getColumnCount();
while (res.next())
{
Object [] rowData = new Object[numberOfColumns];
for (int i = 0; i < rowData.length; ++i)
{
rowData[i] = res.getObject(i+1);
}
dtm.addRow(rowData);
}
gui.jTable1.setModel(dtm);
dtm.fireTableDataChanged();
//////////////////////////
}
catch(Exception e){
System.err.println(e);
e.printStackTrace();
}
finally{
try{
res.close();
statement.close();
conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
}
}}我的testResultSet()方法工作正常。现在,如何更改我的代码,使其工作,或什么是最简单的代码要做。DefaultTableModel从…ResultSet?提前谢谢。编辑:我收到java.lang.IllegalStateException: SQLite JDBC: inconsistent internal state错误。
3 回答
HUWWW
TA贡献1874条经验 获得超12个赞
FillTable(MyTable, "select * Customers;");
public void FillTable(JTable table, String Query){ try { CreateConnection(); Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery(Query); //To remove previously added rows while(table.getRowCount() > 0) { ((DefaultTableModel) table.getModel()).removeRow(0); } int columns = rs.getMetaData().getColumnCount(); while(rs.next()) { Object[] row = new Object[columns]; for (int i = 1; i <= columns; i++) { row[i - 1] = rs.getObject(i); } ((DefaultTableModel) table.getModel()).insertRow(rs.getRow()-1,row); } rs.close(); stat.close(); conn.close(); } catch(InstantiationException | IllegalAccessException | SQLException e) { }}
料青山看我应如是
TA贡献1772条经验 获得超8个赞
import net.proteanit.sql.DbUtils; try { CreateConnection(); PreparedStatement st =conn.prepareStatement("Select * from ABC;"); ResultSet rs = st.executeQuery(); tblToBeFilled.setModel(DbUtils.resultSetToTableModel(rs)); conn.close(); } catch(Exception ex) { JOptionPane.showMessageDialog(null, ex.toString()); }
添加回答
举报
0/150
提交
取消