JDBC for SQL Server - Herong's Tutorial Examples - v3.14, by Herong Yang
Using ResultSetMetaData Objects to List All Fields
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:
The tutorial program below shows a good example of how to use ResultSetMetaData:
/* ListResultFields.java * Copyright (c) HerongYang.com. All Rights Reserved. */ import java.sql.*; public class ListResultFields { public static void main(String [] args) { Connection con = null; try { // Obtaining a connection to SQL Server con = DriverManager.getConnection( "jdbc:sqlserver://localhost\\SQLEXPRESS;" + "user=herong;password=T0pSecret;" + "database=AdventureWorks2019"); // 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 (Exception e) { e.printStackTrace(); } } }
Run this Java program, you will see a list columns (fields) of the system view, sys.objects:
Result set columns: name, nvarchar, 128 object_id, int, 10 principal_id, int, 10 schema_id, int, 10 parent_object_id, int, 10 type, char, 2 type_desc, nvarchar, 60 create_date, datetime, 23 modify_date, datetime, 23 is_ms_shipped, bit, 1 is_published, bit, 1 is_schema_published, bit, 1
Table of Contents
JDBC (Java Database Connectivity) Introduction
Microsoft SQL Server Express Edition
Microsoft JDBC Driver for SQL Server
►Microsoft JDBC Driver - Query Statements and Result Sets
Commonly Used JDBC Class Methods
Calling createStatement() and executeQuery
Receiving ResultSet Objects from executeQuery
Closing ResultSet Objects - res.close()
Looping through ResultSet with res.next()
Retrieving Field Values using res.get*() Methods
►Using ResultSetMetaData Objects to List All Fields
Microsoft JDBC Driver - DatabaseMetaData Object
Microsoft JDBC Driver - DDL Statements
Microsoft JDBC Driver - DML Statements
SQL Server - PreparedStatement
SQL Server CLOB (Character Large Object) - TEXT
SQL Server BLOB (Binary Large Object) - BLOB
Using Connection Pool with JDBC
JDBC-ODBC Bridge Driver - sun.jdbc.odbc.JdbcOdbcDriver
JDBC-ODBC Bridge Driver - Flat Text Files
JDBC-ODBC Bridge Driver - MS Access