Note: Read the Code example disclaimer for important legal information.
import java.sql.*; /** ResultSetMetaDataExample.java This program demonstrates using a ResultSetMetaData and a ResultSet to display all the metadata about a ResultSet created querying a table. The user passes the value for the table and library in. **/ public class ResultSetMetaDataExample { public static void main(java.lang.String[] args) { if (args.length != 2) { System.out.println("Usage: java ResultSetMetaDataExample <library> <table>"); System.out.println("where <library> is the library that contains <table>"); System.exit(0); } Connection con = null; Statement s = null; ResultSet rs = null; ResultSetMetaData rsmd = null; try { // Get a database connection and prepare a statement. Class.forName("com.ibm.db2.jdbc.app.DB2Driver"); con = DriverManager.getConnection("jdbc:db2:*local"); s = con.createStatement(); rs = s.executeQuery("SELECT * FROM " + args[0] + "." + args[1]); rsmd = rs.getMetaData(); int colCount = rsmd.getColumnCount(); int rowCount = 0; for (int i = 1; i <= colCount; i++) { System.out.println("Information about column " + i); System.out.println(" Name..........: " + rsmd.getColumnName(i)); System.out.println(" Data Type.....: " + rsmd.getColumnType(i) + " ( " + rsmd.getColumnTypeName(i) + " )"); System.out.println(" Precision.....: " + rsmd.getPrecision(i)); System.out.println(" Scale.........: " + rsmd.getScale(i)); System.out.print (" Allows Nulls..: "); if (rsmd.isNullable(i)==0) System.out.println("false"); else System.out.println("true"); } } catch (Exception e) { // Handle any errors. System.out.println("Oops... we have an error... "); e.printStackTrace(); } finally { // Ensure we always clean up. If the connection gets closed, the // statement under it closes as well. if (con != null) { try { con.close(); } catch (SQLException e) { System.out.println("Critical error - cannot close connection object"); } } } } }