我希望在 jtable
中显示 SQL 数据。第一步是创建一个 tablemodel
:
public DefaultTableModel createTableModel(String sqlStatement) {
int rowCount = 0;
int colCount = 0;
Vector data = new Vector();
Vector columnnames = new Vector();
String sql = sqlStatement;
try {
open();
ResultSet rs = befehl.executeQuery(sql);
ResultSetMetaData metaData = rs.getMetaData();
for(int i = 1; i<=metaData.getColumnCount();i++)
columnnames.add(metaData.getColumnName(i));
DefaultTableModel model = new DefaultTableModel(null,columnnames);
close();
return model;
} catch (SQLException e) {
e.printStackTrace();
close();
return null;
}
}
如果我的SQL语句选择整个表,则可以正常工作:SELECT * FROM test;
,但是如果我只想显示前两列:Select ColumnName1, ColumName2 from test;
,我会得到一个ArrayIndexOutOfBoundsException
。我一直认为columncount
取决于resultSet
,而resultSet
取决于SQL语句。我该如何获得正确的columncount
?
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 >= 2
at java.util.Vector.elementAt(Vector.java:470)
at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:294)
at sun.swing.SwingUtilities2.convertColumnIndexToModel(SwingUtilities2.java:1841)
at javax.swing.JTable.convertColumnIndexToModel(JTable.java:2585)
at javax.swing.JTable.getValueAt(JTable.java:2720) at Main.KassePanel.<init>(KassePanel.java:186)
at Main.Main.<init>(Main.java:36) at Main.Main.main(Main.java:20)