SQL injection
SQL injection is attacker-controlled text becoming part of a query's syntax. The fix is bind parameters, never string concatenation of user input into SQL.
Detailed Explanation
format!("select * from users where name = '{name}'") is the bug. If name is x' or '1'='1, the query's meaning changes. The database runs the attacker's SQL with the application's credentials. This is still the way databases get dumped, even in new Rust services, because someone built dynamic SQL with format!.
Bind parameters keep data out of syntax. query("select * from users where name = $1").bind(name) sends the query and the value on separate channels. The engine never parses name as SQL. SQLx's query! macros, Diesel's eq(name), and SeaORM's filters all bind. Raw sql_query with a formatted string does not, unless you still bind.
Dynamic ORDER BY and identifier names cannot be bound as values — they are syntax. If you must take a sort column from the user, map it through an allow-list enum (match sort { Sort::Name => "name", Sort::Id => "id" }) and use the constant in the SQL. Do not interpolate the raw header.
ORMs are not automatic safety. A raw-SQL escape hatch, a migration runner, or a LIKE pattern you concatenate (% + user + %) can still inject. LIKE binds the whole pattern as a value; that is safe for injection (the user cannot close a quote) and still needs escaping of % and _ if those are not supposed to be wildcards.
When you write SQL: binds for every value. When you write an identifier: allow-list. When you review a PR: search for format! and + near query.
Second-order injection is still injection: you store a string safely with a bind, then later concatenate that stored string into a new query. Treat every string that did not come from your own allow-list as hostile at every use, not only at the HTTP boundary. Logs and admin tools that build SQL from table rows are a frequent miss.
Code Examples
fn unsafe_sql(name: &str) -> String {
format!("select * from users where name = '{name}'")
}
fn safe_plan(name: &str) -> (&'static str, &str) {
("select * from users where name = $1", name)
}
fn main() {
let attack = "x' or '1'='1";
println!("{}", unsafe_sql(attack).contains("or")); // prints: true
let (sql, bind) = safe_plan(attack);
println!("{sql}"); // prints: select * from users where name = $1
println!("{bind}"); // prints: x' or '1'='1 — data, not syntax
}Common Gotchas
`format!` into a query string is injection
Use `$1` / `?` and `.bind`. There is no "I sanitised the quotes" version you should ship.
Identifiers cannot be bound as values
Allow-list column names. Do not interpolate `req.sort` into `ORDER BY`.
Prepared statements are the mechanism
The SQL is parsed once; values arrive later. Rust crates do this when you bind.
A stored procedure that concatenates inside the database is still injection
The language of the caller does not matter if the SQL is assembled from strings anywhere in the stack.