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
- Open a connection
- Create a command
- Execute the command
- Read results (if any)
- 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!