Read Access
-
CREATE
/UPDATE
/DELETE
client modifies database server data:
int result = statement.executeUpdate("UPDATE Person ...");
-
SELECT
client receives copies of database server data:
ResultSet result = statement.executeQuery("SELECT ... FROM Person ...");
-
No standard Collections container e.g.
java.util.List
. -
“Own” collection
java.sql.ResultSet
holding transient database object copies.
We take an example. Suppose our database contains a table of our friends' nicknames and their respective birth dates:
|
|
final Connection conn = DriverManager.getConnection (...);
final Statement stmt = conn.createStatement();
// Step 3: Creating the client side JDBC container holding our data records
final ResultSet data = stmt.executeQuery("SELECT * FROM Friends"); ❶
// Step 4: Dataset iteration
while (data.next()) { ❷
System.out.println(data.getInt("id") ❸
+ ", " + data.getString("nickname") ❹
+ ", " + data.getString("birthdate")); ❺
}
As being mentioned in the introduction to this section the
JDBC™
standard provides a container interface rather than using
|
|
Calling next() prior to actually accessing data on the client side is mandatory! The next() method positions an internal iterator to the first element of our dataset unless the latter being empty. Follow the link address and **read** the documentation. |
|
The access methods have to be chosen according to matching
types. An overview of database/Java™ type
mappings is being given in |
ResultSet
states - New:
resultSet = statement.executeQuery(...)
-
Caution: Data not yet accessible!
- Cursor positioned:
resultSet.next()
returningtrue
-
Data accessible until
resultSet.next()
returnsfalse
. - Closed:
resultSet.next()
returningfalse
-
Caution: Data not longer accessible!
JDBC™ Type | Java™ type |
---|---|
CHAR , VARCHAR , LONGVARCHAR |
String |
NUMERIC , DECIMAL |
java.math.BigDecimal |
BIT |
boolean |
TINYINT |
byte |
... |
... |
Shamelessly copied from JDBC Types Mapped to Java Types.
Java™ Type | JDBC™ type |
---|---|
String |
CHAR , VARCHAR , LONGVARCHAR |
java.math.BigDecimal |
NUMERIC |
boolean |
BIT |
... |
... |
Shamelessly copied from Java Types Mapped to JDBC Types.
int getInt(int columnIndex)
double getDouble(int columnIndex)
Date getDate(int columnIndex)
...
Object getObject(int columnIndex)
Best SQL to Java type match.
|
|
Caveat: May impact performance.
|
|
Caveat: Error prone on schema evolution.
We now present a series of exercises thereby exploring important aspects of JDBC™ read access.