【问题标题】:How to return the column count, column names, and column types from a specified table in Java?如何从Java中的指定表中返回列数、列名和列类型?
【发布时间】:2021-05-29 16:55:45
【问题描述】:

我的作业是打印给定输入表的列数、名称和类型。代码如下:

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.");
        }
    }

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

【问题讨论】:

    标签: java mysql sql jdbc


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-08
      • 1970-01-01
      • 2016-06-08
      • 2011-08-04
      • 2013-10-17
      • 2022-12-19
      相关资源
      最近更新 更多