This section describes how to call the res.getMetaData method to obtain the ResultSetMetaData object, which can be used to list all fields in the result set.
The ResultSet object returned by a SELECT statement also contains
column (field) names, lengths and types. You can use res.getMetaData()
to retrieve them into a ResultSetMetaData object, which offers the following methods
to allow to get different information:
getColumnCount() -
Returns the number of columns in this ResultSet object.
getColumnName(int column) -
Get the designated column's name.
getColumnTypeName(int column) -
Retrieves the designated column's database-specific type name.
getPrecision(int column) -
Get the designated column's specified column size.
The tutorial program below shows a good example of how to use ResultSetMetaData:
/**
* ListResultFields.java
* Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
*/
import java.sql.*;
public class ListResultFields {
public static void main(String [] args) {
Connection con = null;
try {
// Load Microsoft JDBC Driver 1.0
Class.forName(
"com.microsoft.sqlserver.jdbc.SQLServerDriver");
// Obtaining a connection to SQL Server
con = DriverManager.getConnection(
"jdbc:sqlserver://localhost:1269;"
+ "user=sa;password=HerongYang;"
+ "database=AdventureWorksLT");
// Getting result meta data
Statement sta = con.createStatement();
ResultSet res = sta.executeQuery(
"SELECT * FROM sys.objects"
+ " WHERE type_desc='USER_TABLE'");
ResultSetMetaData rmd = res.getMetaData();
System.out.println("Result set columns:");
for (int i=1; i<=rmd.getColumnCount(); i++) {
String name = rmd.getColumnName(i);
String type = rmd.getColumnTypeName(i);
int size = rmd.getPrecision(i);
System.out.println(" "+name+", "+type+", "+size);
}
con.close();
} catch (java.lang.ClassNotFoundException e) {
System.err.println("ClassNotFoundException: "
+e.getMessage());
} catch (SQLException e) {
System.err.println("SQLException: "
+e.getMessage());
}
}
}
Run this Java program, you will see a list columns (fields) of the system view, sys.objects: