executeQuery() can be used to execute select statement and it will return ResultSet object. When statement.executeQuery(...) is executed, a ResultSet object will be opened (created). The ResultSet object can be used to fetch the data from the database server.

A Java application can take the information about one row at a time from the ResultSet object. The row that is accessed by the Java application is called as the current row of the result set. When the result set is opened current row will be "BEFORE FIRST ROW".

When rs.getRow() is called, it will return a number indicating the current row. 0 will be returned when the current row is either "BEFORE FIRST ROW" or "AFTER LAST ROW".

rs.next() method tries to move to the next available row. This method returns true if it is able to move to the next row. This method returns a false if there is no next row.

getString() method returns a String. If we want the column value as an integer, we can use getInt(). As part of ResultSet interface serveral getters are provided with the names like getString(), getInt(). getFloag(), getDouble(), etc...


SQLDemo

/**
* A demo class to explain executeQuery()
* @author Santhosh Reddy Mandadi
* @since 11-Jun-2012
* @version 1.0
*/

import java.sql.*;

public class SQLDemo
{
public static void main(String[] args) throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = DriverManager.getConnection("jdbc:oracle:@localhost:1521:xe","scott","tiger");
String vsql;
vsql = "SELECT * FROM PRODUCTS";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(vsql);
while(resultSet.next())
{
System.out.println("Current row: "+resultSet.getRow());
System.out.println("Product ID: "+resultSet.getString(1));
System.out.println("Product Name: "+resultSet.getString(2));
System.out.println("Product Price: "+resultSet.getString(3));
System.out.println("**************************************");
}
}
}
In the above application, we're passing the column numbers to getString() method. Instead of this, we can pass the names of the columns as shown below

rs.getInt("PID");
rs.getString("PNAME");
rs.getDouble("PRICE");