Getter methods and type conversion

exercise No. 33

Q:

Apart from type mappings the JDBC access methods like getString() may also be used for type conversion. Modify Figure 812, “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.

The next series of exercises aims on a more powerful implementation of our person data insertion application in the section called “Gui authentication: The real McCoy”.

Figure 820. Problem: null value ambiguity Slide presentation Create comment in forum
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 821. Resolving null value ambiguity Slide presentation Create comment in forum
final int count = resultSet.getInt("numProducts");

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

See wasNull().