如何从Java ResultSet确定列计数?

时间:2013-02-27 20:50:53

标签: java sql swing jtable resultset

我想在jtable中显示SQLdata。第一步是创建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)

1 个答案:

答案 0 :(得分:1)

您应该使用 DatabaseMetaData 而不是 ResultSetMetaData 。我已经完成了一个名为 dbproxy 的java项目,该项目旨在操纵和访问关系数据库的结构(元数据)。我很快就会把它变成一个开源项目。看我的代码:

@Override
public List<ColumnDetail> getColumns(String table) throws SQLException {
    List<ColumnDetail> columnList = new ArrayList<ColumnDetail>();
    ResultSet resultSet = null;
    String catalog = getCatalog();
    String schema = getSchema();

    try {
        DatabaseMetaData databaseMetaData = connection.getMetaData();
        if(databaseMetaData == null) {
            return columnList;
        }
        resultSet = databaseMetaData.getColumns(catalog, schema, table, null);
        if(resultSet == null) {
            return columnList;
        }
        while(resultSet.next()) {
            columnList.add(extractColumnDetail(resultSet));
        }
    }
    catch (SQLException e) {
        throw new SQLException("Could not get columns: " + e.toString());
    }
    catch (Exception e) {
        throw new SQLException("Could not get columns: " + e.toString());
    }
    finally {
        DatabaseUtil.close(resultSet);
    }
    return columnList;
}  

参考Apress.JDBC.Metadata.MySQL.and.Oracle.Recipes.A.Problem.Solution.Approach.Mar.2006