Getter methods and type conversion

exercise No. 11

Q:

Apart from type mappings the JDBC access methods like getString() may also be used for type conversion. Modify Figure 911, “Accessing friend's database records ” by:

What do you observe?

A:

Modifying our iteration loop:

// Step 4: Dataset iteration
while (data.next()) {
    System.out.println(data.getString("id") 
           + ", " + data.getInt("nickname") 
           + ", " + data.getString("birthdate"));
}

We observe:

Calling getString() for a database attribute of type INTEGER does not cause any trouble: The value gets silently converted to a string value.

Calling getInt(String) for the database field of type CHAR yields an (expected) Exception:

Exception in thread "main" java.sql.SQLException: Invalid value for getInt() - 'Jim'
  at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
...

We may however provide compatible data records:

DELETE FROM Friends;
INSERT INTO Friends VALUES (1, '31', '1991-10-10');

This time our application executes perfectly well:

1, 31, 1991-10-10

Conclusion: The JDBC driver performs a conversion from a string type to an integer similar like the parseInt(String) method.

Figure 919. Problem: null value ambiguity Slide presentation
final int count = resultSet.getInt("numProducts");

Problem: Two possibilities in case of count == 0:

  1. DB attribute numProducts is 0 (zero).

  2. DB attribute numProducts is null.


Figure 920. Resolving null value ambiguity Slide presentation
final int count = resultSet.getInt("numProducts");

if (resultSet.wasNull()) {
...
} else {
...
}

See wasNull().