Getter methods and type conversion
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:
We observe:
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:
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. |
final int count = resultSet.getInt("numProducts");
Problem: Two possibilities in case of count == 0
:
-
DB attribute numProducts is 0 (zero).
-
DB attribute numProducts is
null
.
final int count = resultSet.getInt("numProducts");
if (resultSet.wasNull()) {
...
} else {
...
}
See wasNull()
.