madhavi
madhavi

Reputation: 1

how to get the column names(dynamically without hardcoding the columnheaders) of a table from database using collections in java

how to get the column names(dynamically without hardcoding the columnheaders) of a table from database using collections in java

Upvotes: 0

Views: 680

Answers (2)

Michał Niklas
Michał Niklas

Reputation: 54302

You can get database columns via interface DatabaseMetaData getColumns()

After reading save names from returned resultset in some collection.

Upvotes: 0

pinichi
pinichi

Reputation: 2205

What do you use for? Basically you're always able to get table's meta from DB. If you only need for process the result, maybe something like this.

public static void getResultSetMetaData(Connection con) {
   try {
      String SQL = "SELECT TOP 10 * FROM Person.Contact";
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery(SQL);
      ResultSetMetaData rsmd = rs.getMetaData();

      // Display the column name and type.
      int cols = rsmd.getColumnCount();
      for (int i = 1; i <= cols; i++) {
         System.out.println("NAME: " + rsmd.getColumnName(i) + " " + "TYPE: " + rsmd.getColumnTypeName(i));
      }
      rs.close();
      stmt.close();
   }
   catch (Exception e) {
      e.printStackTrace();
   }
}

Upvotes: 1

Related Questions