SQL injection and how to stop it

MySQL Course · lesson 9 of 21 · 4 min read

The vulnerability that comes from building a query out of strings.

Open this lesson in the learning hub

Key points

  • Concatenating user input into SQL lets the user change what the query means, not just its data.
  • Input ' OR '1'='1 turns a login check into a condition that is always true.
  • A prepared statement sends the query shape first and the values separately.
  • The database then treats the value as data forever - it can never become syntax.
  • Escaping by hand is not a substitute; there is always an encoding you did not think of.

Example

// NEVER - the input becomes part of the query
String sql = "SELECT * FROM users WHERE name = '" + input + "'";

// ALWAYS - shape and data travel separately
PreparedStatement ps = conn.prepareStatement(
    "SELECT * FROM users WHERE name = ?");
ps.setString(1, input);        // stays data, whatever it contains

Prepared statements are not a style preference - they are the only reliable defence.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the MySQL Course course, and every lesson in it is listed on the MySQL Course contents page.