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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Database Programming.
Lesson complete
Earn the 3 college credits for Database Programming
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Advanced Techniques for Protecting Database Systems →← 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 →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every credit course with PRO →
Why take it here
Why students take Database Programming with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
How do you write a parameterized query in Python?
Can you use a parameter for a table or column name?
How do you use sp_executesql to prevent SQL injection in SQL Server?
About the Database Programming course
How many college credits is Database Programming?
How much does Database Programming cost and what is included?
Which universities accept UPI Study credits?
How long does Database Programming take?
How are the exams done?
How do my credits reach my college?
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
3 credits · NCCRSEnroll →