Learning about a ResultSet using ResultSetMetaData methods

You cannot always know the number of columns and data types of the columns in a table or result set. This is true especially when you are retrieving data from a remote data source.

About this task

When you write programs that retrieve unknown ResultSets, you need to use ResultSetMetaData methods to determine the characteristics of the ResultSets before you can retrieve data from them.

ResultSetMetaData methods provide the following types of information:
  • The number of columns in a ResultSet
  • The qualifier for the underlying table of the ResultSet
  • Information about a column, such as the data type, length, precision, scale, and nullability
  • Whether a column is read-only

Procedure

After you invoke the executeQuery method to generate a ResultSet for a query on a table, follow these basic steps to determine the contents of the ResultSet:

  1. Invoke the getMetaData method on the ResultSet object to create a ResultSetMetaData object.
  2. Invoke the getColumnCount method to determine how many columns are in the ResultSet.
  3. For each column in the ResultSet, execute ResultSetMetaData methods to determine column characteristics.

    The results of ResultSetMetaData.getColumnName call reflects the column name information that is stored in the catalog for that data server.

Example

The following code demonstrates how to determine the data types of all the columns in the employee table. The numbers to the right of selected statements correspond to the previously-described steps.
Figure 1. Using ResultSetMetaData methods to get information about a ResultSet
String s;
Connection con;
Statement stmt;
ResultSet rs;
ResultSetMetaData rsmtadta;
int colCount
int mtadtaint;
int i;
String colName;
String colType;
…
stmt = con.createStatement();     // Create a Statement object
rs = stmt.executeQuery("SELECT * FROM EMPLOYEE"); 
                                  // Get the ResultSet from the query
rsmtadta = rs.getMetaData();      // Create a ResultSetMetaData object  1 
colCount = rsmtadta.getColumnCount();                                   2 
                                  // Find number of columns in EMP
for (i=1; i<= colCount; i++) {                                          3 
 colName = rsmtadta.getColumnName();    // Get column name
 colType = rsmtadta.getColumnTypeName();
                                        // Get column data type
 System.out.println("Column = " + colName + 
  " is data type " + colType);
                                        // Print the column value
}