Prepared Statement
Definition
A prepared statement, or parameterized query, is a feature used to execute the same or similar database statements repeatedly with high efficiency. The key security benefit is that it separates the SQL query structure from the data, making it immune to SQL injection.
Why It Matters
Using prepared statements is the single most effective defense against SQL injection attacks. It is the modern, standard way to execute database queries with user-provided data.
Contextual Example
Instead of building a query string like `"SELECT * FROM users WHERE name = '" + userName + "'"` (vulnerable), a developer uses a prepared statement like `PREPARE stmt FROM "SELECT * FROM users WHERE name = ?"; SET @userName = "Alice"; EXECUTE stmt;`. The database treats the user input purely as data, not as part of the command.
Common Misunderstandings
- Prepared statements are supported by almost all modern database drivers and libraries.
- In addition to security, they can also improve performance if the same query is executed many times with different data.