Retrieving data using SELECT

You can retrieve data using the executeQuery method of a PreparedStatement, which queries the database with a user-defined SQL statement. This method returns the query result as a ResultSet. The ResultSet can then be traversed to fetch the queried data.

Navigating the ResultSet object

A ResultSet contains the following methods that allow you to navigate through the query results of a SQL SELECT statement:

  • next   Move to the next row.

  • previous   Move to the previous row.

Retrieving data using a ResultSet
To SELECT data from a database
  1. Prepare a new SQL statement as a String.

    String sql_string = 
        "SELECT * FROM Department ORDER BY dept_no";
  2. Pass the String to the PreparedStatement.

    PreparedStatement select_statement = 
        conn.prepareStatement(sql_string);
    
  3. Execute the statement and assign the query results to a ResultSet.

    ResultSet cursor = 
        select_statement.executeQuery();
  4. Traverse through the ResultSet and retrieve the data.

    // Get the next row stored in the ResultSet.
    cursor.next();
    
    // Store the data from the first column in the table.
    int dept_no = cursor.getInt(1);
    
    // Store the data from the second column in the table.
    String dept_name = cursor.getString(2);
  5. Close the ResultSet to free resources.

    cursor.close();
  6. Close the PreparedStatement to free resources.

    select_statement.close()