Java Reference
In-Depth Information
Notice how inefficient the source code is. What if we want to retrieve 50 rows? Should we perform the gets
50 times each?! That does not seem right. We need to improve our data retrieval. In fact, we will use the returned
Boolean values to build a loop to access the result set. We included the Boolean value println statements to demonstrate
that the first two times the next method was executed there were rows to move the cursor to and the returned value
was true . The third time next was executed there was no row, therefore, a false value was returned.
4.
Comment out the statements added in step 2.
5.
Add the following select statement:
rs = stmt.executeQuery(
"SELECT empname, empnum, payrate, exempts" +
" FROM tntdb.employee");
This select will only retrieve four columns. Note that two of the columns contain non-string data.
6.
Add the following code:
while (rs.next()){
System.out.println(rs.getString(1) + rs.getString(2) +
rs.getDouble(3) + " " + rs.getInt(4)); }
This code defines a loop that moves the cursor to each row. When there are no more rows (i.e., the next method
returns a false value), the loop will end. For each row, the appropriate getter retrieves each column's data and the
println statement displays the information.
7.
Run DBAccess as a Java application.
The results will be as follows:
Driver class found!
Connection created!
Statement created!
Mary Worker 111 17.5 3
Joe Programmer 222 17.5 2
8.
Comment out the statements added in step 5 and 6.
9.
Add the following to display all the rows and columns:
rs = stmt.executeQuery("SELECT * FROM tntdb.employee");
while (rs.next()){
System.out.println(rs.getString(1) + rs.getString(2) +
rs.getString(3) + rs.getString(4) + rs.getString(5) +
rs.getString(6) + rs.getDouble(7) + " " +
rs.getInt(8));
}
10.
Run DBAccess as a Java application.
Search WWH ::




Custom Search