European Windows 2019 Hosting BLOG

BLOG about Windows 2019 Hosting and SQL 2019 Hosting - Dedicated to European Windows Hosting Customer

SQL Server Hosting - HostForLIFE :: SQL Injection: Complete Guide with Examples and Proper Solutions

clock May 22, 2026 07:45 by author Peter

One of the most serious and prevalent online security flaws is SQL Injection. Attackers can access, alter, or remove database data by inserting malicious SQL code into application requests. If queries are not handled correctly, applications built using technologies like ASP.NET, PHP, Java, Node.js, Python, or any backend connected to a database may be vulnerable.

What is SQL Injection?
SQL Injection occurs when user input is directly concatenated into SQL queries without validation or parameterization.
Vulnerable Example

string query = "SELECT * FROM Users WHERE Username='" + txtUsername.Text +
               "' AND Password='" + txtPassword.Text + "'";

If a user enters:
' OR 1=1 --

Then the query becomes:
SELECT * FROM Users
WHERE Username='' OR 1=1 --'
AND Password=''


Since 1=1 is always true, authentication is bypassed.

Types of SQL Injection
1. Authentication Bypass

Used to login without valid credentials.

Attack Input
' OR '1'='1

2. Data Extraction
Attackers steal database information.

Example
UNION SELECT name, password FROM Users

3. Data Deletion
Attackers can delete records.

Example
'; DELETE FROM Users --

4. Blind SQL Injection
Attackers retrieve data indirectly using TRUE/FALSE conditions.

Example
' AND 1=1 --

Real-World Vulnerable Code Examples
Example 1: Vulnerable Login API in ASP.NET
Wrong Method
string query = "SELECT * FROM Users WHERE Email='" + email +
               "' AND Password='" + password + "'";

SqlCommand cmd = new SqlCommand(query, con);


Problem
If attacker enters:
admin' --

The query becomes:
SELECT * FROM Users WHERE Email='admin' --' AND Password=''

Password check is skipped.

Proper Solution: Parameterized Query
Secure Method
string query = "SELECT * FROM Users WHERE Email=@Email AND Password=@Password";

SqlCommand cmd = new SqlCommand(query, con);

cmd.Parameters.AddWithValue("@Email", email);
cmd.Parameters.AddWithValue("@Password", password);


Why Secure?
The database treats input as data, not executable SQL.

Example 2: Search Function Vulnerability

Vulnerable Code
string query = "SELECT * FROM Products WHERE ProductName LIKE '%" + keyword + "%'";

Attack
%' OR 1=1 --

Secure Solution
string query = "SELECT * FROM Products WHERE ProductName LIKE @keyword";

SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@keyword", "%" + keyword + "%");


Example 3: Dynamic SQL in Stored Procedure
Vulnerable Stored Procedure
CREATE PROCEDURE GetUser
    @Name NVARCHAR(100)
AS
BEGIN
    DECLARE @SQL NVARCHAR(MAX)

    SET @SQL = 'SELECT * FROM Users WHERE Name=''' + @Name + ''''

    EXEC(@SQL)
END


Dangerous Because

Attackers can inject SQL through @Name.

Secure Stored Procedure

CREATE PROCEDURE GetUser
    @Name NVARCHAR(100)
AS
BEGIN
    SELECT * FROM Users WHERE Name = @Name
END

Best Practices to Prevent SQL Injection
1. Always Use Parameterized Queries

Recommended
cmd.Parameters.Add("@Id", SqlDbType.Int).Value = id;

Avoid
WHERE Id=" + id

2. Use Stored Procedures Properly
Stored procedures are safe only if they avoid dynamic SQL concatenation.

Safe
SELECT * FROM Employee WHERE EmployeeID=@EmployeeID

Unsafe
SET @SQL='SELECT * FROM Employee WHERE ID=' + @ID

3. Validate User Input
Validate:

  • Length
  • Data type
  • Allowed characters
  • Email format
  • Numeric values

Example
if(!int.TryParse(txtId.Text, out int id))
{
    return;
}

4. Apply Least Privilege Principle
Database users should only have required permissions.

Example
Application user should NOT have:

  • DROP DATABASE
  • ALTER TABLE
  • DELETE access (if unnecessary)

5. Hide Detailed Database Errors
Bad
SQL Exception near 'DROP TABLE'

Good
Something went wrong. Please try again.

Log actual errors internally.

6. Use ORM Frameworks
ORMs automatically parameterize queries.

Examples:

  • Entity Framework
  • Dapper
  • Hibernate

7. Sanitize Dynamic SQL Carefully
If dynamic SQL is unavoidable:

  • Use whitelist validation
  • Avoid direct concatenation
  • Use sp_executesql

Secure Dynamic SQL
DECLARE @SQL NVARCHAR(MAX)
SET @SQL = 'SELECT * FROM Users WHERE Name=@Name'

EXEC sp_executesql
    @SQL,
    N'@Name NVARCHAR(100)',
    @Name


SQL Injection Testing Examples
Common Payloads
' OR 1=1 --

admin' --

' UNION SELECT NULL,NULL --

'; DROP TABLE Users --


Secure Login API Example (.NET Core)
[HttpPost]
public IActionResult Login(LoginModel model)
{
    using(SqlConnection con = new SqlConnection(connectionString))
    {
        string query = @"SELECT COUNT(*)
                         FROM Users
                         WHERE Email=@Email
                         AND Password=@Password";
        SqlCommand cmd = new SqlCommand(query, con);
        cmd.Parameters.AddWithValue("@Email", model.Email);
        cmd.Parameters.AddWithValue("@Password", model.Password);
        con.Open();
        int count = (int)cmd.ExecuteScalar();
        if(count > 0)
        {
            return Ok("Login Success");
        }
        else
        {
            return Unauthorized();
        }
    }
}

Additional Security Layers

Use These Together

Security MeasurePurpose

Parameterized Queries

Prevent SQL execution

Input Validation

Block invalid data

WAF (Web Application Firewall)

Detect attacks

HTTPS

Secure transmission

Logging & Monitoring

Detect suspicious activity

Rate Limiting

Prevent brute force

Common Developer Mistakes

MistakeRisk

String concatenation in SQL

Injection vulnerability

Trusting frontend validation

Attackers bypass frontend

Using admin DB account

Full database compromise

Dynamic SQL without validation

Remote execution

Exposing SQL errors

Information leakage

Interview Questions on SQL Injection

Q1. What is SQL Injection?
SQL Injection is a vulnerability where attackers inject malicious SQL code through user input to manipulate database queries.

Q2. How do parameterized queries prevent SQL Injection?
Parameterized queries separate SQL commands from user data, preventing execution of malicious input.

Q3. Are Stored Procedures always safe?
No. Stored procedures using dynamic SQL concatenation can still be vulnerable.

Conclusion
SQL Injection remains one of the top cybersecurity threats because many applications still build queries using string concatenation.

The best protection methods are:

  • Parameterized queries
  • Proper input validation
  • Secure stored procedures
  • Least privilege database access
  • ORM frameworks
  • Error handling and monitoring

Following secure coding practices can prevent attackers from stealing or damaging sensitive database information.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

 



SQL Server Hosting - HostForLIFE :: How to Use Entity Framework Core to Connect SQL Server to C#?

clock May 5, 2026 10:02 by author Peter

One of the most frequent and crucial tasks in contemporary.NET programming is connecting SQL Server with a C# application using Entity Framework Core. Instead of writing raw SQL queries, developers may interface with databases using strongly typed C# objects thanks to Entity Framework Core (EF Core), an Object Relational Mapper (ORM).

This method lowers boilerplate code, increases productivity, and simplifies application maintenance.

What is Entity Framework Core
Entity Framework Core is a lightweight, extensible, and cross-platform ORM framework. It enables developers to:

  • Map database tables to C# classes
  • Perform CRUD operations using LINQ
  • Handle relationships and migrations

Prerequisites
Before starting, ensure you have:

  • .NET SDK installed
  • SQL Server installed (or SQL Server Express)
  • Visual Studio or any preferred IDE

Step 1: Install Required NuGet Packages
Install the following packages in your project:
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer


Microsoft.EntityFrameworkCore.Tools

You can install them using Package Manager Console:
Install-Package Microsoft.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools


Step 2: Create a Model Class
Create a simple model that represents a database table.

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
}


Step 3: Create DbContext Class
DbContext acts as a bridge between your application and the database.

using Microsoft.EntityFrameworkCore;

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }

    public DbSet<User> Users { get; set; }
}


Step 4: Configure Connection String
Add the connection string in appsettings.json:
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=MyDatabase;Trusted_Connection=True;TrustServerCertificate=True;"
  }
}


Step 5: Register DbContext in Program.cs
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));


This step enables dependency injection for the database context.

Step 6: Run Migrations

Migrations help create and update the database schema.
Add-Migration InitialCreate
Update-Database


This will generate the database and tables automatically.

Step 7: Perform CRUD Operations
Insert Data

var user = new User { Name = "John" };
context.Users.Add(user);
context.SaveChanges();


Fetch Data
var users = context.Users.ToList();


Update Data
var user = context.Users.First();
user.Name = "Updated Name";
context.SaveChanges();


Delete Data
context.Users.Remove(user);
context.SaveChanges();


Common Mistakes to Avoid

  • Incorrect connection string configuration
  • Forgetting to run migrations
  • Not registering DbContext in dependency injection
  • Using synchronous calls in high-load applications

Real-World Use Case
In a typical web application, EF Core is used to:

  • Store user data
  • Manage product catalogs
  • Handle orders and transactions

It simplifies database interaction and improves development speed.

Conclusion

Any.NET developer must be able to connect SQL Server using C# using Entity Framework Core. You can establish a clear, scalable, and effective data access layer by following the preceding instructions. EF Core offers sophisticated capabilities like migrations, LINQ querying, and change tracking in addition to reducing the requirement for raw SQL.


HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

 



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in