Skip to content

SQL in Applications: Parameterized Queries and SQL Injection

Beginning of the lesson

SQL in Applications: Parameterized Queries and SQL Injection

How real programs send SQL safely -- and how attackers break the ones that do it wrong

Big Idea: An application almost never types SQL by hand -- it builds query strings from data that came from users. If that data is glued directly into the query text, an attacker can smuggle in their own SQL. The single most important defense is the parameterized query (also called a prepared statement): you send the query template and the values on separate channels, so user input can never change what the query means.
By the end you will be able to:
  • describe how an application connects to a database and sends SQL,
  • explain why building queries by string concatenation is dangerous,
  • read the anatomy of a SQL injection attack (login bypass and UNION data theft),
  • write a parameterized query / prepared statement that neutralises the attack,
  • apply least privilege so a compromised query does as little damage as possible.

1. How an application sends SQL

You have been running SQL by hand in a client. A web or mobile app does the same thing, just programmatically. It opens a connection to the database through a driver (a library such as mysql2 for Node.js, JDBC for Java, or psycopg for Python), sends a query as text, and reads back the rows.

The database has no idea a "user" exists. It receives a string, parses it into a query, runs it, and returns a result set. That is the crux of the whole topic: the database trusts whatever SQL text it is handed. If your code lets an outsider influence that text, the outsider is effectively writing SQL on your server.

Everything below uses one small shop database. Let us build it once.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers