Working with Databases Using ADO.NET

Connect your C# app to SQL Server

Posted by Rodrigo Castro on December 15, 2024

ADO.NET is the standard way to connect your C# applications to relational databases like SQL Server.

🔌 Connecting to SQL Server

You’ll need a connection string (ask your DBA or use SQL Server Express):

1
string connString = "Server=localhost;Database=TestDb;User Id=sa;Password=YourPassword;";

🚦 Basic Steps

  1. Open a connection
  2. Create a command
  3. Execute the command
  4. Read results (if any)
  5. Close the connection

📝 Example: Query Data

1
2
3
4
5
6
7
8
9
10
11
12
13
using System.Data.SqlClient;

using (SqlConnection conn = new SqlConnection(connString))
{
    conn.Open();
    string sql = "SELECT Id, Name FROM Users";
    SqlCommand cmd = new SqlCommand(sql, conn);
    SqlDataReader reader = cmd.ExecuteReader();
    while (reader.Read())
    {
        Console.WriteLine($"{reader["Id"]}: {reader["Name"]}");
    }
}

💾 Insert Data Example

1
2
3
4
5
6
7
8
using (SqlConnection conn = new SqlConnection(connString))
{
    conn.Open();
    string sql = "INSERT INTO Users (Name) VALUES (@name)";
    SqlCommand cmd = new SqlCommand(sql, conn);
    cmd.Parameters.AddWithValue("@name", "Alice");
    cmd.ExecuteNonQuery();
}

⚠️ Don’t Forget

  • Always use using to auto-close connections.
  • Parameterize queries to prevent SQL injection.

Next: Connecting to SQL Server and Oracle!