BackendBench
Coffee
Spot the Bug #52

The first parameter is number one

A easy 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.

easySQL and JDBC mistakesbuggy line: 6

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

What is wrong

JDBC parameter and column indexes start at 1, not 0. setString(0, ...) throws an SQLException about an invalid parameter index.

The fix

ps.setString(1, status);

How to avoid it next time

JDBC is one-based, unlike arrays and lists. Named parameters in Spring JdbcTemplate avoid the counting.

Want the background? Read JDBC and prepared statements 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โ† #51#53 โ†’

Frequently asked questions

What is the bug in "The first parameter is number one"?

JDBC parameter and column indexes start at 1, not 0. setString(0, ...) throws an SQLException about an invalid parameter index. The faulty line is line 6: ps.setString(0, status);

How do I fix it?

Replace it with: ps.setString(1, status);. JDBC is one-based, unlike arrays and lists. Named parameters in Spring JdbcTemplate avoid the counting.

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