The Dangers of String Formatting in SQL
You'll learn why using Python's string formatting tools to build SQL queries opens the door to catastrophic security vulnerabilities.
The Tempting But Deadly Shortcut
When you first connect Python to a database, it's tempting to build SQL queries using familiar string manipulation: f-strings, .format(), or simple concatenation. After all, you just need to plug a username into a query, right?
Wrong. This is one of the most dangerous mistakes in programming.
# DANGEROUS - Never do this!
username = input("Enter username: ")
query = f"SELECT * FROM users WHERE username = '{username}'"
cursor.execute(query)
Why This Is Catastrophic
Imagine a user enters: admin' OR '1'='1
Your f-string cheerfully creates:
SELECT * FROM users WHERE username = 'admin' OR '1'='1'
The attacker just tricked your database into returning all users because '1'='1' is always true. Worse, they could inject '; DROP TABLE users; -- and delete your entire database.
The analogy: You're building a sentence by gluing together pieces of paper. An attacker hands you a paper that says "ignore everything before this and do what I say instead." You glue it in without reading it first.
String formatting treats user input as trusted SQL code. It doesn't distinguish between your query structure and malicious commands hidden in data.
The same danger applies to .format() and + concatenation—any method that mixes user input directly into SQL strings.
Key Takeaway: Never use f-strings, .format(), or string concatenation to insert user input into SQL queries—they create SQL injection vulnerabilities that can expose, corrupt, or destroy your entire database.