Java Reference
In-Depth Information
Again, assuming that rs is a valid ResultSet variable and the cursor is pointing at a row, the following would
retrieve the empnum column's text data and assign it to a String variable called empNum:
empNum = rs.getString(empnum);
In the above example, the column was identified by the column name. You can also reference a column by its
number. For instance, assuming empNum is the first column, the following statement would also work:
empNum = rs.getString(1);
Unfortunately, the column number is dependent on the select statement. For instance, if the select statement had
specified the fields as follows:
SELECT empname, empnum FROM tntdb.employee
empname would be column 1 and empnum would be column 2.
Generally, specifying column numbers and retrieving the result set columns from left to right provides the
fastest retrieval.
Tutorial: Retrieving Data from a Database
Let's get some data out of those databases:
1.
In DBAccess, comment out the insert statement and the return value println statement.
2.
Add the following statements:
rs = stmt.executeQuery("SELECT * FROM tntdb.employee");
System.out.println(rs.next());
System.out.println(rs.getString(1) + rs.getString(2));
System.out.println(rs.next());
System.out.println(rs.getString(1) + rs.getString(2));
System.out.println(rs.next());
3.
Run DBAccess as a Java application.
The results will be the following:
Driver class found!
Connection created!
Statement created!
true
111 Mary Worker
true
222 Joe Programmer
false
Even though the select returned all the columns, we only retrieved data from the first two columns. This is not
a terrible mistake. However, if only two columns are required, for efficiency's sake, the select should specify only
those columns.
 
Search WWH ::




Custom Search