Menu

How to Connect to a SQL Database in C# Using ADO.NET

Connecting to a SQL database in C# is easier than you think, and thanks to ADO.NET, you can do it with just a few lines of code.

Whether you're building a robust enterprise app or just tinkering with databases for fun, understanding how to make this connection is essential. Let’s break it down!

Step 1: Install the Required Package

First things first, make sure you have the System.Data.SqlClient namespace available.

This is built into .NET Framework, but if you're using .NET Core or later, you should install the Microsoft.Data.SqlClient package via NuGet:

Install-Package Microsoft.Data.SqlClient

Step 2: Define Your Connection String

A connection string contains all the necessary information to connect to your database. Here’s an example of a basic connection string for SQL Server:

string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
  • Server: The name of your SQL Server instance (e.g., localhost, 127.0.0.1, or a remote server).
  • Database: The name of the database you want to connect to.
  • User Id & Password: Your SQL Server credentials (if using SQL authentication). If you’re using Windows Authentication, replace these with Integrated Security=True;.

Step 3: Create the Connection

Now, let’s connect to the database using SqlConnection:

using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "Server=myServer;Database=myDB;User Id=myUser;Password=myPass;";
        
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            try
            {
                connection.Open();
                Console.WriteLine("Connection successful!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Connection failed: " + ex.Message);
            }
        }
    }
}

Breaking It Down:

  • We wrap our SqlConnection in a using block to ensure proper disposal after use.
  • connection.Open(); establishes the connection.
  • We catch any errors to avoid app crashes (always a good practice).

Step 4: Execute a Simple Query

Now that we’re connected, let’s run a basic SQL query:

using (SqlCommand command = new SqlCommand("SELECT TOP 5 * FROM Users", connection))
{
    using (SqlDataReader reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            Console.WriteLine($"User: {reader["Name"]}, Email: {reader["Email"]}");
        }
    }
}

What’s Happening Here?

  • We use SqlCommand to define our query.
  • ExecuteReader() fetches the data.
  • We iterate through the SqlDataReader to display the results.

Wrapping Up

And there you have it! You’ve successfully connected to a SQL database in C# using ADO.NET. Now you can run queries, fetch data, and build amazing database-driven applications.

Feeling adventurous? Try inserting, updating, or deleting records using ExecuteNonQuery(). Happy coding! 🚀

0
87

Related

Reading a file line by line is useful when handling large files without loading everything into memory at once.

✅ Best Practice: Use File.ReadLines() which is more memory efficient.

Example

foreach (string line in File.ReadLines("file.txt"))
{
    Console.WriteLine(line);
}

Why use ReadLines()?

Reads one line at a time, reducing overall memory usage. Ideal for large files (e.g., logs, CSVs).

Alternative: Use StreamReader (More Control)

For scenarios where you need custom processing while reading the contents of the file:

using (StreamReader reader = new StreamReader("file.txt"))
{
    string? line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

Why use StreamReader?

Lets you handle exceptions, encoding, and buffering. Supports custom processing (e.g., search for a keyword while reading).

When to Use ReadAllLines()? If you need all lines at once, use:

string[] lines = File.ReadAllLines("file.txt");

Caution: Loads the entire file into memory—avoid for large files!

3
224

String interpolation, introduced in C# 6.0, provides a more readable and concise way to format strings compared to traditional concatenation (+) or string.Format(). Instead of manually inserting variables or placeholders, you can use the $ symbol before a string to directly embed expressions inside brackets.

string name = "Walt";
string job = 'Software Engineer';

string message = $"Hello, my name is {name} and I am a {job}";
Console.WriteLine(message);

This would produce the final output of:

Hello, my name is Walt and I am a Software Engineer

String interpolation can also be chained together into a multiline string (@) for even cleaner more concise results:

string name = "Walt";
string html = $@"
    <div>
        <h1>Welcome, {name}!</h1>
    </div>";
36
125

When working with URLs in C#, encoding is essential to ensure that special characters (like spaces, ?, &, and =) don’t break the URL structure. The recommended way to encode a string for a URL is by using Uri.EscapeDataString(), which converts unsafe characters into their percent-encoded equivalents.

string rawText = "hello world!";
string encodedText = Uri.EscapeDataString(rawText);

Console.WriteLine(encodedText); // Output: hello%20world%21

This method encodes spaces as %20, making it ideal for query parameters.

For ASP.NET applications, you can also use HttpUtility.UrlEncode() (from System.Web), which encodes spaces as +:

using System.Web;

string encodedText = HttpUtility.UrlEncode("hello world!");
Console.WriteLine(encodedText); // Output: hello+world%21

For .NET Core and later, Uri.EscapeDataString() is the preferred choice.

26
262