SQL Injection Prevention in Python — ELI5

Imagine you’re ordering at a deli counter. You write your order on a slip: “One turkey sandwich.” The person behind the counter reads it and makes your sandwich.

Now imagine someone writes: “One turkey sandwich AND ALSO give me everything in the cash register.

If the deli worker just follows whatever is on the slip without thinking, they’d hand over the cash too. That’s ridiculous for a deli, but it’s exactly how SQL injection works with databases.

When a website asks you to type your username and it builds a database query with whatever you typed, a clever attacker can type something like their name plus extra database commands. If the website just jams the text straight into the query, the database follows all the commands — including the sneaky ones.

An attacker could read all the passwords, delete tables full of data, or even take control of the whole server. All by typing something crafty into a login form.

The fix in Python is surprisingly simple: never mix user input directly into database commands. Instead, you send the command and the data separately. The database receives the command with a placeholder that says “a name goes here,” and then receives the name as a separate piece. It treats the name as pure data — not as a command — no matter what tricky text is inside.

This is called a parameterized query, and every serious Python database library supports it. It’s the difference between the deli worker blindly following any scribbled instruction versus having a fixed order form where the only thing you can fill in is the sandwich type.

The one thing to remember: SQL injection happens when user text gets mixed into database commands — and parameterized queries stop it by keeping commands and data completely separate.

pythonsecuritydatabasesweb

See Also