如何用数据库填充JTable中的数据?

我想显示一个JTable,它按原样显示来自数据库表的数据。

到目前为止,我已经使用了JTable来显示Object [] []中的数据。

我知道一种显示数据的方法是先将数据库表转换为Object [] [],但是还有其他方法更简单但更强大,更灵活。


慕慕森
浏览 745回答 3
3回答

慕姐4208626

用ResultSet填充jTable的最佳方法先决条件1)结果集“ rs”中填充了您需要的数据。2)在操作之前创建JTable“ jTable1” 3)在操作之前实现表头实作&nbsp; &nbsp; &nbsp; &nbsp; java.sql.ResultSet rs = datacn.executeSelectQuery(query);&nbsp; &nbsp; &nbsp; &nbsp; //Filling JTable with Result set&nbsp; &nbsp; &nbsp; &nbsp; // Removing Previous Data&nbsp; &nbsp; &nbsp; &nbsp; while (jTable1.getRowCount() > 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ((DefaultTableModel) jTable1.getModel()).removeRow(0);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; //Creating Object []rowData for jTable's Table Model&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; int columns = rs.getMetaData().getColumnCount();&nbsp; &nbsp; &nbsp; &nbsp; while (rs.next())&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Object[] row = new Object[columns];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int i = 1; i <= columns; i++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; row[i - 1] = rs.getObject(i); // 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ((DefaultTableModel) jTable1.getModel()).insertRow(rs.getRow() - 1,row);&nbsp; &nbsp; &nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java