Explain Codes LogoExplain Codes Logo

What are good ways to prevent SQL injection?

sql
sql-injection-prevention
parameterized-queries
orm-security
Nikita BarsukovbyNikita Barsukov·Mar 10, 2025
TLDR

Prevent SQL injection by leveraging parameterized queries, a practice that uses placeholders (?) in SQL statements, subsequently binding them to actual values by the database engine. Here's a concise Python example using psycopg2:

cur = conn.cursor() cur.execute("SELECT * FROM users WHERE username = %s AND password = %s", (username, password))

Key lessons: Always keep command and data separate — never insert user input directly into statements. Stick to prepared statements, bind parameters, enforce input validation and data type restrictions to keep your application secure.

The application of parameterized queries

SqlCommand and SqlParameter for the .NET warriors

In the .NET universe, make sure to use SqlCommand, coupled with SqlParameter. This method provides a robust layer of type-checking, thanks to SqlDbType, forming a dependable shield against injection attacks:

using(var connection = new SqlConnection(connectionString)) { var command = new SqlCommand("SELECT * FROM Users WHERE Username = @username AND Password = @password", connection); command.Parameters.Add("@username", SqlDbType.NVarChar).Value = username; // Yes, we validate usernames. command.Parameters.Add("@password", SqlDbType.NVarChar).Value = password; // Your secret is safe with us 😉 connection.Open(); command.ExecuteNonQuery(); // Fire that command! }

ORM for the picky abstractionist

ORM tools such as Entity Framework or NHibernate abstract the SQL generation process and inherently employ parameterized queries. Injection risk? Reduced to a great extent!

// Entity Framework example var user = context.Users.FirstOrDefault(u => u.Username == username && u.Password == password); // Hunting for users, are we?