简体   繁体   中英

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

I have an assignment for homework to print out the amount of columns, its names and types for a given table that is input. Here is the code:

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

However, when I run this code, it gives me a more than obvious number of columns for the table than it has, only the last column name, and the incorrect number of column types. How can I make it so that it produces the correct number of columns, displays all of the column names, and the correct amount of column types? PS the primary key part works fine.

I figured it out, I wasn't printing in the correct location. Sue me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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