我想在jtable
. 第一步是创建一个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
,而依赖于 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)