University of Cincinnati logo and link  
SELECT queries and ResultSets
 
  UC ingot When we issue UPDATE, DELETE, and INSERT commands, we're essentially sending data to the database.  But a SELECT command returns data that we want to use.
 
  • So, we save that data in a ResultSet object.  Thus, we need a different return type than the one provided to us in executeUpdate(), so we must use executeQuery().

  • ResultSet rs = stmt.executeQuery("SELECT * FROM students");
     

    • Think of a ResultSet as an ArrayList or Vector.  It is a collection of data through which we can iterate.
    • In our earlier example, we wanted to print out the data from each student.  We used this type of loop to do so:

    •  ResultSet rs = stmt.executeQuery("Select * from student");

       int recordNo = 0;

       while(rs.next()) {
        recordNo++;
        %>
        <tr>
         <td colspan = 4>
         Record # <%=recordNo%>
         </td>
        <tr>
        <tr>
         <td>Name: <%=rs.getString("name")%></td>
          <td>ID: <%=rs.getString("bearcatID")%></td>
         <td>Gender: <%=rs.getString("gender")%></td>
         <td>Major: <%=rs.getString("major")%></td>
        </tr>
        <%
       }

      If this weren't a JSP, we could do something very similar:

       ResultSet rs = stmt.executeQuery("Select * from student");

       int recordNo = 0;

       while(rs.next()) {
        recordNo++;
      System.out.println(recordNo + ": ");
        System.out.println("Name: " + rs.getString("name"));
          System.out.println("ID: " + rs.getString("bearcatID"));
         System.out.println("Gender:" + rs.getString("gender"));
         System.out.println("Major: " + rs.getString("major"));
       }
       

    • There are some alternate ways to do this.
      • You can supply the column number instead of column name.
      • getString() will reasonably convert any data type to a String. This is a nice feature.
 JDBC 2