Java Reference
In-Depth Information
only, similar to reading data from an input stream. Once the cursor is positioned over
a row, we can use one of following methods to retrieve data from a specific column in
the current row:
intVal = resultSet.getInt("name of int field");
lngVal = resultSet.getLong("name of bigint field");
strVal = resultSet.getString("name of varchar field");
dblVal = resultSet.getDouble("name of double field");
fltVal = resultSet.getFloat("name of float field");
The program in Display 19.13 can run once the database is created with the
program given in Display 19.12. It retrieves and outputs all rows in the table by
executing a
SELECT
query with no
WHERE
clause and then retrieves and outputs only
those rows with any
author_id
greater than 1. Invoke the
close( )
method to free
resources when finished using a
ResultSet
object.
Finally, we can change the contents of an existing row using the SQL
UPDATE
command. In the
UPDATE
command, we specify the table, field(s) to change, new
value(s), and a
WHERE
clause to indicate which rows should be changed. If the
WHERE
clause is omitted, then every row in the table is updated. The syntax is described in the
box “Common SQL Statements.” Display 19.14 shows an example where the
URL
field
is changed to a new value entered by the user. The
URL
field is only changed for the row
that matches the
author_id
entered by the user.
Display 19.13
Retrieving Rows with the SELECT Statement
(part 1 of 3)
The database must be created (Display 19.12)
before running the program.
1
import java.sql.Connection
;
2 import java.sql.DriverManager;
3 import java.sql.ResultSet;
4 import java.sql.SQLException;
5 import java.sql.Statement;
6
public class
ReadDB
7 {
8
private static final
String driver =
"org.apache.derby.jdbc.EmbeddedDriver";
9
private static final
String protocol = "jdbc:derby:";
10 /*
11
Outputs the author, ID, and URL of the current
12
author in the ResultSet
13 */
14
public static void
displayNameRow(ResultSet rs)
throws
SQLException
15 {
16
int
id = rs.getInt("author_id");
17 String author = rs.getString("author");
18 String url = rs.getString("url");
The accessor methods
throw the checked exception
SQLException.
(continued)