SQL Server Database Connection In C# Using ADO.NET | Raw SQL 🚀Query

R M Shahidul Islam Shahed
3 min readFeb 20, 2024

In modern software development, the efficient management and manipulation of data are paramount. SQL (Structured Query Language) databases are the backbone for storing, retrieving, and managing data in various applications. Leveraging SQL databases with programming languages like C# opens up a world of possibilities for developers to create robust and dynamic applications.

SQL Server Database Connection In C# Using ADO.NET | Raw SQL 🚀Query

This introduction focuses on establishing a connection to a SQL Server database using C# and ADO.NET, a popular data access technology in the .NET framework. Additionally, we drive into the execution of raw SQL queries, offering developers fine-grained control over database operations.

To connect to a SQL Server database in C# using ADO.NET, you can follow these steps:

  1. Install the necessary NuGet packages: You’ll need the System.Data.SqlClient package, which is included by default in .NET Framework projects.
  2. Write the C# code/console app to establish a connection to the SQL Server database.
dotnet add package System.Data.SqlClient --version 4.8.6
SQL Server Database Connection In C# Using ADO.NET | Raw SQL 🚀Query

Required Installations

  • .NET SDK 8.0
  • VS Code/Visual Studio Latest Version

Here’s a Basic Example Using C# Console App:

SQL Server Database Connection In C# Using ADO.NET | Raw SQL 🚀Query
using RawSQLConn;
using System.Data.SqlClient;


using (SqlConnection connection = new(Helper.connectionString))
{
try
{
connection.Open();
Console.WriteLine("Connection successful!");
var result = Helper.GetAllDepartment(connection);

foreach (var item in result)
{
Console.WriteLine($"Branch Id{item.Id}, Branch Nme: {item.Name}");
}

connection.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}

--

--