This section describes how to receive the ResultSet object returning from the executeQuery() method.
When you execute a SQL SELECT statement with the executeQuery() method,
you need receive the returning ResultSet object with a variable.
This ResultSet object variable represents the data that are generated
by the SELECT query statement.
There are two types of methods available on the ResultSet object:
Moving the internal pointer to set a specific row as the current row of the result set.
For example, next() sets the next row as the current row.
Retrieving the value from a specific field of the current row.
For example, getInt(1) retrieves the value from the first field as an integer.
getint("Age") retrieves the value from a field named as "Age".
The tutorial below shows you how to receive the ResultSet object
and the value from the first column of the first row:
/**
* GetServerDate.java
* Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
*/
import java.sql.*;
public class GetServerDate {
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");
// Checking the database name
Statement sta = con.createStatement();
ResultSet res = sta.executeQuery("SELECT GETDATE()");
res.next();
Date today = res.getDate(1);
System.out.println("Server date: "+today);
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 program, you will get something like this: