在 C# 中连接数据库并操作数据,一般可以通过 ADO.NET 或 Entity Framework 来实现。以下是连接数据库和操作数据的基本步骤:
使用 ADO.NET 连接数据库
- 引用
System.Data.SqlClient
命名空间。 - 创建数据库连接对象
SqlConnection
,并传入连接字符串。 - 使用
SqlConnection
打开数据库连接。 - 创建
SqlCommand
对象,编写 SQL 命令。 - 执行 SQL 命令并处理结果。
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connStr = "Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;";
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
string sql = "SELECT * FROM TableName";
using (SqlCommand cmd = new SqlCommand(sql, conn))
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader["ColumnName"]);
}
}
}
}
}
使用 Entity Framework 连接数据库
- 安装 Entity Framework NuGet 包。
- 创建
DbContext
类,表示数据库上下文。 - 定义实体类,表示数据库表。
- 使用 LINQ 查询或操作数据。
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
class MyDbContext : DbContext
{
public DbSet<MyEntity> MyEntities { get; set; }
}
class MyEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main()
{
using (var db = new MyDbContext())
{
var entities = db.MyEntities.ToList();
foreach (var entity in entities)
{
Console.WriteLine(entity.Name);
}
}
}
}