This section describes how to retrieve field values of the current row in the ResultSet object with the res.get*() methods.
Once the result set is captured in an object, you can think of it
as a "table" with rows and columns (fields).
As shown in the previous tutorial, you can use res.next() to loop through each row.
Then use res.get*() methods to retrieve field values of the current row
by giving the field name or field position as shown below:
type value = res.getType(i); // retrieve by position
// position value starts from 1
type value = res.getType(name); // retrieve by name
The tutorial Java program below shows you how to list tables in the current database.
Multiple attributes of each table are retrieved and displayed:
/**
* GetFieldValues.java
* Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
*/
import java.sql.*;
public class GetFieldValues {
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 field values
Statement sta = con.createStatement();
ResultSet res = sta.executeQuery(
"SELECT * FROM sys.objects"
+ " WHERE type_desc='USER_TABLE'");
System.out.println("User Tables:");
while (res.next()) {
String name = res.getString("name");
int id = res.getInt(2);
String type = res.getString(7);
System.out.println(" "+name+", "+id+", "+type);
}
con.close();
} catch (java.lang.ClassNotFoundException e) {
System.err.println("ClassNotFoundException: "
+e.getMessage());
} catch (SQLException e) {
System.err.println("SQLException: "
+e.getMessage());
}
}
}
If you run this script, you will get something like: