Skip to Main Content
Java Enterprise Best Practices
book

Java Enterprise Best Practices

by O'Reilly Java Authors
December 2002
Intermediate to advanced content levelIntermediate to advanced
288 pages
9h 46m
English
O'Reilly Media, Inc.
Content preview from Java Enterprise Best Practices

Use wasNull( ) Checks

SQL NULL is a very useful tool that, unfortunately, is frequently abused. A good database application uses NULL in situations in which a row lacks a value. For example, if you have an application in which one of the attributes of the Person table is numPets, you should use NULL to indicate that you do not know how many pets they have. Without NULL, you would have to use a bogus value such as -1.

Your JDBC code should always be checking for possible NULL values from nullable columns using the wasNull( ) method in ResultSet. The actual value that JDBC returns for NULL values in getter methods is undefined. Your code to check the number of pets, for example, should look like the following fragment:

conn = ds.getConnection(  );
stmt = conn.prepareStatement("SELECT numPets FROM Person WHERE personID = ?");
stmt.setLong(1, 13933L);
rs = stmt.executeQuery(  );
if( rs.next(  ) ) {
    pets = rs.getInt(1);
    if( rs.wasNull(  ) ) {
        pets = -1; // Java has no concept of null for numerics!
    }
}
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Moving to Java 9: Better Design and Simpler Code

Moving to Java 9: Better Design and Simpler Code

Trisha Gee
Java EE 8 High Performance

Java EE 8 High Performance

Romain Manni-Bucau

Publisher Resources

ISBN: 0596003846Supplemental ContentErrata Page