Muokkaa

Jaa


Using result set metadata

Download JDBC driver

To query a result set for information about the columns that it contains, the Microsoft JDBC Driver for SQL Server implements the SQLServerResultSetMetaData class. This class contains numerous methods that return information in the form of a single value.

To create a SQLServerResultSetMetaData object, you can use the getMetaData method of the SQLServerResultSet class.

In the following example, an open connection to the AdventureWorks2022 sample database is passed in to the function, the getMetaData method of the SQLServerResultSet class is used to return a SQLServerResultSetMetaData object, and then various methods of the SQLServerResultSetMetaData object are used to display information about the name and data type of the columns contained within the result set.

public static void getResultSetMetaData(Connection con) {
    try(Statement stmt = con.createStatement();) {
        String SQL = "SELECT TOP 10 * FROM Person.Contact";

        ResultSet rs = stmt.executeQuery(SQL);
        ResultSetMetaData rsmd = rs.getMetaData();

        // Display the column name and type.
        int cols = rsmd.getColumnCount();
        for (int i = 1; i <= cols; i++) {
            System.out.println("NAME: " + rsmd.getColumnName(i) + " " + "TYPE: " + rsmd.getColumnTypeName(i));
        }
    }
    // Handle any errors that may have occurred.
    catch (SQLException e) {
        e.printStackTrace();
    }
}

See also

Handling metadata with the JDBC driver