繁体   English   中英

如何返回Java中指定表的列数、列名、列类型?

[英]How to return the column count, column names, and column types from a specified table in Java?

我有一项家庭作业,要打印出输入给定表的列数、名称和类型。 这是代码:

public void printTableInfo(String tableName) throws DLException{
        String catalog = null;
        String schemaPattern = null;
        String tableNamePattern = tableName;
        String columnNamePattern = null;
        int columnCount = 0;
        String columnName = null;
        int columnType = 0;
        String columnPrimaryKeys = null;
        try {
            DatabaseMetaData dbmd = connection.getMetaData();

            ResultSet result = dbmd.getColumns(catalog, schemaPattern, tableNamePattern, columnNamePattern);
            ResultSetMetaData rsmd = result.getMetaData();
            columnCount = rsmd.getColumnCount();
            ResultSet primaryKeys = dbmd.getPrimaryKeys(catalog, schemaPattern, tableNamePattern);

            while(result.next()) {
                columnName = result.getString(4);
                columnType = result.getInt(5);
            }
            while(primaryKeys.next()) {
                columnPrimaryKeys = primaryKeys.getString(4);
            }
            System.out.println("\nColumn count: " + columnCount + ", Column names: " + columnName + ", Column Types: " + columnType + "\nPrimary Keys: " + columnPrimaryKeys);
        } catch (SQLException sqle) {
            throw new DLException(sqle, "-> Error in processing data printing (SQLException) to the database at printTableInfo() method.");
        }
    }

但是,当我运行此代码时,它给我的表的列数比它有的多,只有最后一个列名和不正确的列类型数。 我怎样才能使它产生正确的列数,显示所有列名和正确数量的列类型? PS主键部分工作正常。

我想通了,我没有在正确的位置打印。 告我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM