BackendBench
Coffee
Spot the Bug #53

A missing age that became zero

A medium Java puzzle in the sql and jdbc mistakes family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

mediumSQL and JDBC mistakesbuggy line: 7

Highlighted: line 7. Play this one as a puzzle without the answer.

What is wrong

getInt returns 0 when the column is NULL. The age is then stored as 0 instead of null, so unknown ages show as newborns and statistics are wrong. wasNull or getObject tells the two cases apart.

The fix

Integer age = rs.getObject("age", Integer.class);

How to avoid it next time

For nullable columns use getObject with the wrapper type, or call wasNull right after the getter.

Want the background? Read ResultSet and mapping rows to objects in the Java concepts library.

About sql and jdbc mistakes

Building SQL by string concatenation invites injection, and a handful of subtle JDBC habits leak connections, load too much data or commit half a change.

In code review: Search for plus signs inside strings passed to executeQuery, createQuery or createNativeQuery. Parameters belong in placeholders, never in the text.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #52#54 โ†’

Frequently asked questions

What is the bug in "A missing age that became zero"?

getInt returns 0 when the column is NULL. The age is then stored as 0 instead of null, so unknown ages show as newborns and statistics are wrong. wasNull or getObject tells the two cases apart. The faulty line is line 7: Integer age = rs.getInt("age");

How do I fix it?

Replace it with: Integer age = rs.getObject("age", Integer.class);. For nullable columns use getObject with the wrapper type, or call wasNull right after the getter.

How do I catch sql and jdbc mistakes in code review?

Search for plus signs inside strings passed to executeQuery, createQuery or createNativeQuery. Parameters belong in placeholders, never in the text.

Is there a new puzzle every day?

Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.

More tools you might need