---
title: "SQL Injection and Prevention in C#"  
description: "SQL Injection is a common security vulnerability that occurs when an attacker manipulates SQL queries by injecting malicious input, potentially allowi"  
author: "ICSM Computer"  
published: 2025-02-12  
updated: 2025-02-12  
canonical: https://www.mindstick.com/blog/305255/sql-injection-and-prevention-in-c-sharp  
category: "ado.net"  
tags: ["c#", "ado.net"]  
reading_time: 3 minutes  

---

# SQL Injection and Prevention in C#

#### SQL Injection and Prevention in C#

SQL Injection is a [common security](https://www.mindstick.com/forum/157835/what-are-some-common-security-threats-that-modern-networks-face-and-how-can-they-be-mitigated) vulnerability that occurs when an attacker manipulates SQL queries by injecting malicious input, potentially allowing [unauthorized access](https://www.mindstick.com/forum/158562/how-can-wireless-networks-be-secured-against-unauthorized-access-and-attacks) to a database.

#### 1. How SQL Injection Works

SQL injection occurs when user input is concatenated directly into SQL queries. Consider the following example:

```plaintext
string query = "SELECT * FROM Users WHERE Username = '" + username + "' AND Password = '" + password + "'";
SqlCommand cmd = new SqlCommand(query, conn);
```

If an attacker inputs:

```plaintext
username: ' OR '1'='1
password: anything
```

The query becomes:

```plaintext
SELECT * FROM Users WHERE Username = '' OR '1'='1' AND Password = 'anything'
```

Since `'1'='1'` always evaluates to `true`, the query bypasses authentication.

#### 2. Preventing SQL Injection in C#

## 2.1. Use Parameterized Queries (Recommended)

Using `SqlCommand` with parameters ensures that user input is treated as data, not SQL code.

## Example:

```cs
string query = "SELECT * FROM Users WHERE Username = @username AND Password = @password";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
    cmd.Parameters.AddWithValue("@username", username);
    cmd.Parameters.AddWithValue("@password", password);
    SqlDataReader reader = cmd.ExecuteReader();
}
```

- **Prevents SQL injection** because input is treated as a value.
- **Avoid** `.AddWithValue()` **for complex types** (e.g., `DateTime`), as it may cause implicit conversion issues.

**2.2. Use [Stored Procedures](https://www.mindstick.com/forum/540/using-stored-procedures-with-entity-framework-in-an-asp-dot-net-application)**

Stored procedures execute predefined SQL logic, [reducing the risk](https://answers.mindstick.com/qa/115612/what-preventive-measures-help-in-reducing-the-risk-of-infectious-viral-diseases) of injection.

## Example:

```plaintext
CREATE PROCEDURE ValidateUser
    @username NVARCHAR(50),
    @password NVARCHAR(50)
AS
BEGIN
    SELECT * FROM Users WHERE Username = @username AND Password = @password
END
```

```cs
using (SqlCommand cmd = new SqlCommand("ValidateUser", conn))
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@username", username);
    cmd.Parameters.AddWithValue("@password", password);
    SqlDataReader reader = cmd.ExecuteReader();
}
```

**2.3. Use ORM ([Entity Framework](https://www.mindstick.com/articles/1566/crud-operations-using-entity-framework-code-first-approach), Dapper)**

ORMs like **Entity Framework (EF)** and **Dapper** abstract direct SQL queries, making them safer.

## Using Entity Framework (EF)

```cs
var user = dbContext.Users
    .FirstOrDefault(u => u.Username == username && u.Password == password);
```

EF generates parameterized queries automatically.

## Using Dapper

```cs
string sql = "SELECT * FROM Users WHERE Username = @Username AND Password = @Password";
var user = connection.QueryFirstOrDefault<User>(sql, new { Username = username, Password = password });
```

**2.4. [Input Validation](https://www.mindstick.com/forum/158627/describe-the-concept-of-an-httprequestvalidationexception-and-its-relevance-in-input-validation) & Escaping**

- **Allowlist validation:** Ensure input meets expected formats (e.g., alphanumeric for usernames).
- **Escape special characters:** If necessary, manually escape single quotes (`'` → `''`).

## 2.5. Principle of Least Privilege

- Avoid using `sa` **(sysadmin) accounts** for [database access](https://www.mindstick.com/blog/766/database-access-in-asp-dot-net).
- Restrict user roles and **deny direct access** to sensitive tables.

**2.6. [Web Application Firewall](https://www.mindstick.com/blog/12608/what-you-need-to-know-about-web-application-firewall) (WAF)**

Use a **WAF** to block suspicious requests containing SQL injection patterns.

#### 3. Summary

**Do it to [prevent SQL Injection](https://www.mindstick.com/forum/776/are-pdo-prepared-statements-sufficient-to-prevent-sql-injection):**

1. Use **Parameterized Queries**
2. Use **Stored Procedures**
3. Use **ORMs like Entity Framework/Dapper**
4. Validate user input

## Don't:

1. Concatenate user input into SQL queries
2. Use dynamic SQL with string interpolation

---

Original Source: https://www.mindstick.com/blog/305255/sql-injection-and-prevention-in-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
