Skip to content
Ameen Abozaid
Planned lessonJNR-025-L04

Dynamic SQL without injection

  • Lesson 4 of 5
  • Junior
On This Lesson 4 topics

This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.

In this lesson

build queries from user input safely.

Planned topics

  • SQL injection: user text becomes part of the SQL command and changes its meaning.
  • Values always go through ? placeholders (PreparedStatement); the database never treats them as SQL.
  • Placeholders cannot be used for column names or ASC/DESC.
  • For a user-chosen sort column, use an allow-list (a fixed map from public names to real column names).
  • Unknown value: reject it or fall back to a default; never paste it in.
Draft outline details

Demonstration

java
private static final Map<String, String> SORTABLE = Map.of("name", "name", "price", "price");

String col = SORTABLE.getOrDefault(sortParam, "name");
String dir = "desc".equalsIgnoreCase(dirParam) ? "desc" : "asc";
String sql = "select id, name, price from product order by " + col + " " + dir;

Check your understanding

Can you pass a column name as a ? parameter?

Show answer

No; use an allow-list.

Practice

Apply this lesson with the module's lab, exercises and quiz.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.