bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/SQL/SQL Database
SQL•SQL Database

SQL Parameters

SQL Parameters - Prevent SQL Injection

SQL parameters (Parameterized Queries) can be used to protect a web site from SQL injections.

A parameterized query is a SQL statement that uses placeholders instead of directly adding the input values into the query text. The placeholders get replaced with the actual values when the query executes. This makes the queries more safe and more reusable.

Most databases support parameterized queries, but the syntax varies:

  • MySQL use ? for parameters
  • SQL Server uses @ for parameters
  • PostgreSQL uses $ for parameters

SQL parameters are added to an SQL query at execution time, in a controlled manner.

ASP.NET Razor Example

userid = getRequestString("UserId");
query = "SELECT *
FROM Users WHERE UserId = @userid";
db.Execute(query, userid);

Note that parameters in SQL Server are presented by a @ marker.

The SQL engine checks each parameter to ensure that it is correct for its column and are treated literally, and not as part of the SQL to be executed.

Another Example

cname = getRequestString("CustomerName");
caddress = getRequestString("Address");
 ccity = getRequestString("City");
 query = "INSERT INTO Customers (CustomerName, Address, City) Values(@cname, @caddress, @ccity)";
db.Execute(query,
 cname, caddress, ccity);

Previous

SQL Injection

Next

SQL Prepared Statements

This chapter

Overview
21

Lessons

50m

Read time

1. SQL CREATE DATABASE Statement2. SQL DROP DATABASE Statement3. SQL BACKUP DATABASE Statement4. SQL CREATE TABLE Statement5. SQL DROP TABLE Statement6. SQL ALTER TABLE Statement7. SQL Constraints8. SQL NOT NULL Constraint9. SQL UNIQUE Constraint10. SQL PRIMARY KEY Constraint11. SQL FOREIGN KEY Constraint12. SQL CHECK Constraint13. SQL DEFAULT Constraint14. SQL CREATE INDEX Statement15. SQL AUTO INCREMENT Field16. SQL Working With Dates17. SQL Views18. SQL Injection19. SQL Parameters20. SQL Prepared Statements21. SQL Hosting

On this page

SQL Parameters - Prevent SQL InjectionASP.NET Razor ExampleAnother Example