To query a result set for information about the columns that it contains, the Microsoft SQL Server 2005 JDBC Driver implements the SQLServerResultSetMetaData class. This class contains numerous methods that return information in the form of a single value.

To create a SQLServerResultSetMetaData object, you can use the getMetaData method of the SQLServerResultSet class.

In the following example, an open connection to the SQL Server 2005 AdventureWorks sample database is passed in to the function, the getMetaData method of the SQLServerResultSet class is used to return a SQLServerResultSetMetaData object, and then various methods of the SQLServerResultSetMetaData object are used to display information about the name and data type of the columns contained within the result set.

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();
   }
}

See Also