C# 数据库连接以及操作

在 C# 中连接数据库并操作数据,一般可以通过 ADO.NET 或 Entity Framework 来实现。以下是连接数据库和操作数据的基本步骤:

使用 ADO.NET 连接数据库

  1. 引用 System.Data.SqlClient 命名空间。
  2. 创建数据库连接对象 SqlConnection,并传入连接字符串。
  3. 使用 SqlConnection 打开数据库连接。
  4. 创建 SqlCommand 对象,编写 SQL 命令。
  5. 执行 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 连接数据库

  1. 安装 Entity Framework NuGet 包。
  2. 创建 DbContext 类,表示数据库上下文。
  3. 定义实体类,表示数据库表。
  4. 使用 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);
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我写代码菜如坤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值