Làm việc với Database trong C# (SQL Server, MySQL) – Phần 14
1. Giới thiệu
C# hỗ trợ nhiều hệ quản trị cơ sở dữ liệu (DBMS) như SQL Server, MySQL, SQLite, PostgreSQL, v.v.
Trong bài này, ta sẽ tập trung vào SQL Server và MySQL, hai hệ DBMS phổ biến nhất.
✅ Công cụ cần thiết:
- SQL Server hoặc MySQL (có thể cài đặt hoặc dùng dịch vụ online như Azure, AWS RDS).
- Visual Studio (hoặc .NET CLI nếu dùng Linux/macOS).
- Thư viện ADO.NET hoặc Entity Framework Core (EF Core).
2. Kết nối SQL Server bằng ADO.NET
ADO.NET là thư viện chuẩn để làm việc với cơ sở dữ liệu trong C#.
2.1. Cài đặt thư viện
👉 Nếu dùng .NET Framework, không cần cài thêm gì.
👉 Nếu dùng .NET Core, cài đặt System.Data.SqlClient:
dotnet add package System.Data.SqlClient
2.2. Kết nối SQL Server bằng ADO.NET
💡 Ví dụ: Kết nối đến SQL Server và lấy dữ liệu từ bảng Students.
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = "Server=localhost;Database=SchoolDB;User Id=sa;Password=yourpassword;";
using SqlConnection conn = new SqlConnection(connectionString);
try
{
conn.Open();
Console.WriteLine("✅ Kết nối SQL Server thành công!");
string query = "SELECT Id, Name, Age FROM Students";
using SqlCommand cmd = new SqlCommand(query, conn);
using SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine($"ID: {reader["Id"]}, Tên: {reader["Name"]}, Tuổi: {reader["Age"]}");
}
}
catch (Exception ex)
{
Console.WriteLine($"❌ Lỗi: {ex.Message}");
}
}
}
📌 Giải thích:
SqlConnectionkết nối đến SQL Server.SqlCommandthực hiện truy vấn SQL.SqlDataReaderđọc dữ liệu từ kết quả truy vấn.usingđảm bảo tài nguyên được giải phóng sau khi dùng.
3. Kết nối MySQL bằng MySql.Data
3.1. Cài đặt thư viện
Để kết nối MySQL trong C#, cài đặt thư viện MySql.Data:
dotnet add package MySql.Data
3.2. Kết nối MySQL và lấy dữ liệu
💡 Ví dụ: Lấy danh sách sinh viên từ MySQL.
using System;
using MySql.Data.MySqlClient;
class Program
{
static void Main()
{
string connectionString = "Server=localhost;Database=SchoolDB;User Id=root;Password=yourpassword;";
using MySqlConnection conn = new MySqlConnection(connectionString);
try
{
conn.Open();
Console.WriteLine("✅ Kết nối MySQL thành công!");
string query = "SELECT Id, Name, Age FROM Students";
using MySqlCommand cmd = new MySqlCommand(query, conn);
using MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine($"ID: {reader["Id"]}, Tên: {reader["Name"]}, Tuổi: {reader["Age"]}");
}
}
catch (Exception ex)
{
Console.WriteLine($"❌ Lỗi: {ex.Message}");
}
}
}
📌 Khác biệt so với SQL Server:
- Thay
SqlConnectionbằngMySqlConnection. - Thay
SqlCommandbằngMySqlCommand. - Thay
SqlDataReaderbằngMySqlDataReader.
4. Thêm, Sửa, Xóa Dữ Liệu
4.1. Thêm dữ liệu vào bảng Students
💡 Ví dụ: Chèn một sinh viên mới vào SQL Server.
string insertQuery = "INSERT INTO Students (Name, Age) VALUES (@name, @age)";
using SqlCommand cmd = new SqlCommand(insertQuery, conn);
cmd.Parameters.AddWithValue("@name", "Nguyễn Văn A");
cmd.Parameters.AddWithValue("@age", 20);
cmd.ExecuteNonQuery();
Console.WriteLine("✅ Đã thêm sinh viên mới!");
📌 Lưu ý:
- Sử dụng
@parameterđể tránh SQL Injection.
4.2. Cập nhật dữ liệu
💡 Ví dụ: Cập nhật tuổi sinh viên có ID = 1.
string updateQuery = "UPDATE Students SET Age = @age WHERE Id = @id";
using SqlCommand cmd = new SqlCommand(updateQuery, conn);
cmd.Parameters.AddWithValue("@age", 22);
cmd.Parameters.AddWithValue("@id", 1);
cmd.ExecuteNonQuery();
Console.WriteLine("✅ Đã cập nhật tuổi sinh viên!");
4.3. Xóa dữ liệu
💡 Ví dụ: Xóa sinh viên có ID = 1.
string deleteQuery = "DELETE FROM Students WHERE Id = @id";
using SqlCommand cmd = new SqlCommand(deleteQuery, conn);
cmd.Parameters.AddWithValue("@id", 1);
cmd.ExecuteNonQuery();
Console.WriteLine("✅ Đã xóa sinh viên!");
5. Sử dụng Entity Framework Core (EF Core)
Thay vì dùng ADO.NET, ta có thể dùng Entity Framework Core để làm việc với database dễ dàng hơn.
5.1. Cài đặt EF Core cho SQL Server
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
5.2. Tạo Model cho bảng Students
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
5.3. Tạo DbContext
using Microsoft.EntityFrameworkCore;
public class SchoolContext : DbContext
{
public DbSet<Student> Students { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlServer("Server=localhost;Database=SchoolDB;User Id=sa;Password=yourpassword;");
}
5.4. Thao tác với Database bằng EF Core
💡 Thêm sinh viên mới
using (var db = new SchoolContext())
{
db.Students.Add(new Student { Name = "Trần Văn B", Age = 21 });
db.SaveChanges();
Console.WriteLine("✅ Đã thêm sinh viên mới!");
}
💡 Lấy danh sách sinh viên
using (var db = new SchoolContext())
{
var students = db.Students.ToList();
students.ForEach(s => Console.WriteLine($"ID: {s.Id}, Tên: {s.Name}, Tuổi: {s.Age}"));
}
📌 Lợi ích của EF Core:
✅ Viết code ngắn gọn, dễ hiểu.
✅ Tránh lỗi SQL Injection.
✅ Tương thích với nhiều loại database.
6. Tổng Kết
✅ ADO.NET giúp kết nối và truy vấn SQL Server/MySQL.
✅ EF Core giúp làm việc với database dễ dàng hơn.
✅ Dùng parameter để tránh SQL Injection.
💡 Bài tiếp theo:
👉 Làm việc với API và Web Services trong C# – Phần 15 🚀