Defending Against SQL Injection — Parameterized Queries, Input Validation, and Best Practices

UPI Study › Courses › Database Programming › Free lessons › Lesson 12.4 Free with a free account

Defending Against SQL Injection — Parameterized Queries, Input Validation, and Best Practices

Database Programming · Chapter 12: Database Security and AuditingSection 12.4 · lesson 73 of 769 min · free with a free account

← How SQL Injection Attacks Exploit Vulnerable Queries — Patterns and Real-World ExamplesNext lesson: Advanced Techniques for Protecting Database Systems →

A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

In this lesson

Stop SQL injection with bound parameters, validation and narrow accounts.

  • Write parameterized queries in SQLite, MySQL, SQL Server and Python
  • Explain why binding keeps crafted input from becoming SQL syntax
  • Use allow-lists for identifiers that placeholders cannot bind
  • Add validation, constraints, narrow accounts and safe error handling as extra layers

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,078 words). Read along, or search it.

Opening Scenario

Repairing the Search Without Banning Quotes

Leo Park repairs the fictional Lantern Books search page. Removing quotation marks would stop some test strings, but it would also damage legitimate names. Can the application accept ordinary punctuation, while ensuring that no supplied value becomes part of the command? The repair starts at the execution boundary. We will bind real values, then add the controls that binding cannot provide.

Sandbox Setup

A Fresh Local Shop Database

This isolated file contains the canonical customer subset: identifiers, first names, cities, and points. It does not alter the shared course baseline. Run the setup. The SQLite shell creates a fresh local shop database, with foreign-key enforcement enabled. Our examples use no server account commands. MySQL and SQL Server account and procedure syntax will appear only as labeled listings.

Parameterized Query

A Named Placeholder for City

A placeholder marks a value position in a parameterized query. Here, at city is a named SQLite parameter, not pasted query text. Run the script. Dot parameter is a shell command that supplies the bound value before the select executes. Matched is three, for Pune. The comparison operates on a value, while the select structure remains fixed. A prepared statement can be reused with different bound values. The safety property is separation at the API and parser boundary, not a promised network-message count.

Binding in Action

Crafted Text Stays a Plain Value

Now supply the crafted text as the parameter value, while keeping exactly the same select statement. Its quotation marks have no grammatical role in that statement. Run it. This is real parameter binding in the SQLite shell, not string replacement inside the displayed query. Matched is zero. None of our customers has that literal city name, so no record qualifies. Binding does not remove unusual text. It prevents that text from becoming an operator or condition, even when the value contains SQL-looking characters.

MySQL Syntax

PREPARE, EXECUTE USING and DEALLOCATE

In MySQL, prepare names a statement containing a question-mark placeholder. Execute using supplies its value, and deallocate prepare releases the prepared statement. The template remains fixed when a different city arrives. A value is supplied through the binding mechanism, rather than joined into the statement. These statements require MySQL, so no SQLite output accompanies them. The conceptual boundary is the same one our shell example just exercised.

SQL Server Syntax

Typed Parameters With sp_executesql

SQL Server uses sp_executesql, with a statement, a parameter declaration, and a supplied value. The declaration gives at city its type. The leading N marks Unicode text, which fits an N varchar parameter. A stored procedure that builds dynamic text still needs this boundary. Calling a procedure does not make concatenated input safe. We are reading server syntax here. SQLite does not implement this procedure, and we are not inventing a result for it.

Application Code

Python Passes Values as a Tuple

Application libraries expose the same separation. In Python's SQLite API, execute receives the fixed query and a separate tuple of values. The comma makes a one-item tuple. The library binds its element to the placeholder; application code does not format it into the query string. MySQL Connector for Python uses a different placeholder spelling. Follow the selected driver's API, and never confuse its markers with ordinary string interpolation. A name such as O'Brien remains valid data. Binding preserves its apostrophe; deleting that character would change the customer's name.

Punctuation Check

An Apostrophe Survives Binding Unchanged

Here is a direct punctuation check. Bind O'Brien as a value, then ask the database to return that value. Run it. The apostrophe remains part of the name, and never becomes a quotation mark in the select statement. The returned name is unchanged. A general ban on apostrophes would reject legitimate data, while binding preserves the value safely.

Input Validation

Type, Length, Format and Range Checks

Input validation checks whether data is meaningful for the application. Perform it on the server, because browser checks can be bypassed. Check type, length, format, and range. An identifier should have the expected numeric form; a quantity should also lie inside the permitted business range. An allow-list accepts known choices. A sort-column selector should map a small set of choices to fixed programmer-written identifiers.

Identifiers

Placeholders Cannot Bind Column Names

Placeholders represent values, not table names, column names, or the direction keyword in order by. Binding a column name would not make it an identifier. A deny-list that strips suspicious characters misses valid variations and damages legitimate input. Use appropriate validation alongside binding, rather than as its replacement.

Database Constraints

STRICT Tables and CHECK Rules

Database constraints add another boundary. But a declared type has engine-specific behavior, so do not assume every integer column rejects text. Run this SQLite example. The first table uses ordinary integer affinity; the second uses strict typing and a quantity check. The first stored type is text. The checked table contains quantity two, which meets its declared range. A strict table rejects incompatible storage types, and a check rejects disallowed values. Binding, validation, and constraints solve different parts of the problem.

Narrow Access

Fixed Procedures and Limited Accounts

A fixed stored procedure can expose one reviewed operation, accepting typed parameters instead of arbitrary query text. Grant execute on that procedure, with the appropriate ownership context, instead of broad table rights. Confirm that it also authorizes the requested business record. If the procedure constructs dynamic SQL, parameterize that statement too. The same rule applies when the value came from a trusted-looking database row. An application account should have only the necessary objects and actions. Separate it from administrators, omit delegation, and keep its secret outside the source code.

Error Handling

Generic Messages, Private Diagnostics

Safe error handling protects operational details. Give visitors a generic failure message with a reference, then record useful diagnostics privately. Redact passwords, tokens, and encryption keys from those diagnostics. A private log is still sensitive data that needs access controls and retention rules. SQL Server try catch can capture a failure and throw a generic message. MySQL handlers and signal provide corresponding server-side building blocks. An application can also catch exceptions at its boundary. Disable production debug pages, and test that neither raw query text nor a stack trace reaches the visitor.

Quick Check

Binding Keeps the Template's Own OR

A new report binds this entire city string, then applies a separate points condition already written in the template. How many customers match this complete query? Pause, and decide. Two matching records. The bound city matches nobody, but Ben and Dara each have points below ninety. Run the query to confirm that result. Binding neutralizes the supplied syntax; it does not remove the programmer's own or condition. Zero ignores that fixed condition. Six treats the supplied characters as executable SQL, which binding prevents.

Key Takeaways

Layered Defenses Around the Execution Boundary

Leo can now accept punctuation without letting it rewrite the search. Bind values through the driver's API at every execution boundary. Validate meaning on the server, and choose identifiers from a fixed allow-list. Use fixed procedures, private errors, and narrow accounts to reduce the remaining opportunities and consequences.

About Database Programming at UPI Study

Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Defending Against SQL Injection — Parameterized Queries, Input Validation, and Best Practices

How do parameterized queries prevent SQL injection?
A parameterized query sends the SQL text with placeholders and supplies the values separately, so the statement's structure is fixed before any value is attached. A value can then only be compared as data and cannot become an operator or a new condition. Binding the text ' OR '1'='1 as a city simply searches for a city with that literal name and finds none. Deleting or banning quotes is not a substitute.
How do you write a parameterized query in Python?
Pass the SQL with placeholders and the values as a separate argument to execute, rather than formatting them into the string. With Python's sqlite3 module, cur.execute('SELECT first_name FROM customers WHERE city = ?', (city,)) binds the value, and the trailing comma makes a one-item tuple. MySQL Connector/Python uses %s placeholders; pass values the same way, never with Python's % operator or f-strings. A name such as O'Brien keeps its apostrophe.
Can you use a parameter for a table or column name?
No, placeholders stand for values only, not table names, column names or keywords such as ASC and DESC in ORDER BY. To let users choose a sort column, map a small set of allowed choices to fixed identifiers written by the programmer, for example name to last_name and city to city, and reject anything else. Stripping suspicious characters with a deny-list misses variations and can damage legitimate input.
How do you use sp_executesql to prevent SQL injection in SQL Server?
Pass the statement, a parameter declaration and the value as separate arguments, for example EXEC sp_executesql N'SELECT first_name FROM customers WHERE city = @city', N'@city nvarchar(50)', @city = @input; The value is bound to the typed parameter instead of being joined into the text. A stored procedure that builds dynamic SQL by concatenation is still vulnerable, so use this form inside procedures as well.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Database Programming.

76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Database Programming
3 credits · NCCRS
Enroll →