Retrieving data using SELECT

The SELECT statement allows you to retrieve information from the database. When you execute a SELECT statement, the PreparedStatement.executeQuery method returns a ResultSet object.

 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();
 See also