BackendBench
Coffee
Spot the Bug #49

Looking up a user by name

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

The name is concatenated into the SQL, so input such as x' or '1'='1 changes the query and returns every user. This is SQL injection. Escaping by hand is fragile.

The fix

PreparedStatement ps = c.prepareStatement("select * from users where name = ?"); ps.setString(1, name); return ps.executeQuery();

How to avoid it next time

Always use bind parameters for values, in JDBC, JPQL and native queries alike.

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โ† #48#50 โ†’

Frequently asked questions

What is the bug in "Looking up a user by name"?

The name is concatenated into the SQL, so input such as x' or '1'='1 changes the query and returns every user. This is SQL injection. Escaping by hand is fragile. The faulty line is line 6: return st.executeQuery("select * from users where name = '" + name + "'");

How do I fix it?

Replace it with: PreparedStatement ps = c.prepareStatement("select * from users where name = ?"); ps.setString(1, name); return ps.executeQuery();. Always use bind parameters for values, in JDBC, JPQL and native queries alike.

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