zhaoch93
zhaoch93

Reputation: 93

The method getColumnName in ResultSetMeta can't return right name of column (jdbc)

I want to get table label of column .like string display in mysql. Like this enter image description here However, when I use getColumnName, It turn out there is some difference between returned string and below string. Like this: enter image description here But It is right in Variables explorer in eclipse when I debug, Like this: enter image description here I can't find other way to get column. It seem returned string is originalColumnName, but how to get ColumnName? Anyone know how to fix it?

There is my code, I know there is other problem in code. Please just assume the type of all column is String.

      public ResultSet DisplayShowTables() throws SQLException
  {
      ResultSet Res = Sta.executeQuery("DESC Code2Name");
      ResultSetMetaData ResMeta = Res.getMetaData();
      String [] ColumnName = new String [ResMeta.getColumnCount()];
      int MetaCount = ResMeta.getColumnCount();
      for (int i = 0; i < MetaCount; i++) {
          ColumnName [i] =  ResMeta.getColumnName(i+1);
    }
      String LeftAlignFormat = "|";
      String Separator = "+";
      for (int i = 0; i < MetaCount; i++) {
          LeftAlignFormat = LeftAlignFormat.concat(" %-20s |");
          Separator =Separator.concat("----------------------+");
    }
      LeftAlignFormat = LeftAlignFormat.concat("%n");
      Separator = Separator.concat("%n");
      if(Res.isBeforeFirst()){
            System.out.format(Separator);
            System.out.format(LeftAlignFormat, ColumnName);
            System.out.format(Separator);   
        }
      while (Res.next()) {
        Vector<String> RowData = new Vector<String>();
        for (int i = 0; i < MetaCount; i++) {
            RowData.add(Res.getString(i+1).toString());
        }
        System.out.format(LeftAlignFormat, RowData);
    }
        if(Res.isAfterLast())
            System.out.format(Separator);
      return Res;
  }

Upvotes: 1

Views: 1174

Answers (1)

Mark Rotteveel
Mark Rotteveel

Reputation: 109282

It looks like DESC is just a shortcut for a query of the information schema with aliases for the columns.

Column aliases can be retrieved with ResultSetMetadata.getColumnLabel(int).

JDBC defines column label as:

Gets the designated column's suggested title for use in printouts and displays. The suggested title is usually specified by the SQL AS clause. If a SQL AS is not specified, the value returned from getColumnLabel will be the same as the value returned by the getColumnName method.

This also means that in almost all situation you should be using getColumnLabel instead of getColumnName.

Upvotes: 7

Related Questions