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:
Example
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
}