Blog Series #3 — SQL Injection: when input becomes a command
A search can change meaning when an application mixes user input with SQL. Follow a C# example with .NET 10 and learn how to fix the flaw using parameterized queries.


Imagine a screen that searches for customers by name. The application receives the text, builds a query, and asks the database for matching records. It seems straightforward, but the way that query is built can let someone change what it does.
SQL Injection happens when an input becomes part of the structure of a command sent to the database. What should be just a name becomes a condition capable of changing the query. This class of weakness is described in CWE-89.
Where the flaw starts
To find a customer called Maria, an application might execute:
SELECT id, name FROM customers WHERE name = 'Maria';
The risk appears when the server builds this text by directly concatenating the incoming value. The quotes delimiting the name and the characters supplied by the user share the same space, with no separation between the instruction and its data.
A search, a report filter, or a URL parameter can carry input to this point. The field on the screen is just the start of the path; the flaw is in how the server constructs the query.
A C# example with .NET 10
This lab uses .NET 10 and the Microsoft.Data.Sqlite package, an ADO.NET provider for SQLite. The database stays in memory while the connection is open; all three customers are fictional, and no database server installation is needed.
With the .NET 10 SDK installed, create a console application and add the package:
dotnet new console --name SqlInjectionLab --framework net10.0
cd SqlInjectionLab
dotnet add package Microsoft.Data.Sqlite --version 10.0.13
Replace the contents of Program.cs with this article's C# blocks, in the order they appear, and execute it with dotnet run. Start with the connection, sample data, and a function to read the results:
using Microsoft.Data.Sqlite;
using var connection = new SqliteConnection("Data Source=:memory:");
connection.Open();
using (var setup = connection.CreateCommand())
{
setup.CommandText = """
CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO customers (id, name)
VALUES (1, 'Maria'), (2, 'João'), (3, 'D''Angelo');
""";
setup.ExecuteNonQuery();
}
static List<(int Id, string Name)> ReadCustomers(SqliteCommand command)
{
using var reader = command.ExecuteReader();
List<(int Id, string Name)> customers = [];
while (reader.Read())
{
customers.Add((reader.GetInt32(0), reader.GetString(1)));
}
return customers;
}
Now imagine that the search receives the value ' OR 1=1 -- , with a space after the two hyphens. This snippet is deliberately vulnerable:
var name = "' OR 1=1 -- ";
using (var vulnerable = connection.CreateCommand())
{
vulnerable.CommandText =
$"SELECT id, name FROM customers WHERE name = '{name}'";
foreach (var customer in ReadCustomers(vulnerable))
{
Console.WriteLine($"{customer.Id}: {customer.Name}");
}
}
The resulting query is:
SELECT id, name FROM customers WHERE name = '' OR 1=1 -- '
The first quote in the input closes the name value. The OR 1=1 adds an always-true condition, and -- causes the rest of the line to be treated as a comment. In this example, the console displays Maria, João, and D'Angelo even though nobody searched for their names.
C# string interpolation only builds the text of CommandText. Placing input inside $"...{name}..." does not create a database parameter.
Even a legitimate input such as D'Angelo breaks the syntax of this concatenation. Removing the apostrophe would damage a valid name and leave the application dependent on fragile filters.
The impact depends on the query and permissions
In this lab, the effect is to broaden a read operation's results. In a real application, this can expose information that the query should restrict. Other vulnerable paths may allow changes or deletions, depending on the SQL executed and the database account's privileges.
An injection in a SELECT does not automatically mean that any command can run or that every table is accessible. The database, driver, query, and permissions determine the reach. Still, a single unauthorized read can compromise customer data.
The fix: pass values as parameters
Keep the SQL structure fixed and pass the name separately to the database API:
using (var safe = connection.CreateCommand())
{
safe.CommandText = "SELECT id, name FROM customers WHERE name = $name";
safe.Parameters.Add("$name", SqliteType.Text).Value = name;
var customers = ReadCustomers(safe);
Console.WriteLine(customers.Count);
}
The $name inside the SQL is a placeholder. Parameters.Add creates a text parameter, and Value receives the value to bind to it. That same input is now searched for as a literal name. Since no customer has that name, the console displays 0.
This $name is part of SQLite's parameter syntax, not C# string interpolation. The Microsoft documentation explains this binding between placeholders and values. When adapting the example to another database, follow your provider's API. Building the string with the input first and then calling Prepare() leaves the flaw in place.
What still needs attention
A parameter represents a value, such as a name or date. To let a user choose a sort column, map known options to fixed columns in code. Table names, column names, and keywords such as ASC and DESC require this handling of the query structure.
The same care applies to ORMs and stored procedures: SQL queries built manually inside them must also separate values from instructions. The OWASP guidance explains these defenses.
Give the application account only the permissions it needs. A read-only account should access only the data it requires. This reduces the impact of a flaw. Authorization rules for users and organizations remain necessary even with parameterized queries.
How to verify the fix
Still in the lab, confirm that ordinary names and apostrophes work, while the input that previously changed the SQL no longer broadens the results:
var cases = new (string Name, int[] ExpectedIds)[]
{
("Maria", [1]),
("D'Angelo", [3]),
("' OR 1=1 -- ", [])
};
foreach (var testCase in cases)
{
using var command = connection.CreateCommand();
command.CommandText = "SELECT id, name FROM customers WHERE name = $name";
command.Parameters.Add("$name", SqliteType.Text).Value = testCase.Name;
var actualIds = ReadCustomers(command).Select(customer => customer.Id);
if (!actualIds.SequenceEqual(testCase.ExpectedIds))
{
throw new InvalidOperationException();
}
}
Console.WriteLine("OK");
When you execute the complete program with dotnet run, you will see the three customers from the vulnerable query, the 0 from the parameterized query, and the OK from the checks. The using blocks dispose of commands and readers; the connection is disposed of at the end of the program.
In your application, turn these cases into regression tests and review the places that construct SQL. This small set verifies the example; it does not prove that every application path is protected.
Bring DevSecOps into your workflow with runtz
Include query reviews in changes that access the database. Start analyzing security risks at runtz.dev.
Updated Oct 28, 2026



