溫馨提示×

c#連接sqlserver數(shù)據(jù)庫的方法是什么

小億
107
2024-05-29 12:52:10
欄目: 云計算

在 C# 中連接 SQL Server 數(shù)據(jù)庫的方法通常有兩種:使用 ADO.NET 和 Entity Framework。

  1. 使用 ADO.NET:
using System.Data.SqlClient;

string connectionString = "Data Source=YourServerName;Initial Catalog=YourDatabaseName;User ID=YourUsername;Password=YourPassword";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    
    // 執(zhí)行 SQL 查詢、插入、更新、刪除等操作
    
    connection.Close();
}
  1. 使用 Entity Framework: 首先需要安裝 Entity Framework NuGet 包,并創(chuàng)建一個 DbContext 類來表示數(shù)據(jù)庫連接,并利用 LINQ 查詢數(shù)據(jù)。
using System.Data.Entity;

public class YourDbContext : DbContext
{
    public YourDbContext() : base("name=YourConnectionStringName") { }

    public DbSet<YourEntity> YourEntities { get; set; }
}

在應(yīng)用程序中使用 DbContext 連接數(shù)據(jù)庫:

using (var dbContext = new YourDbContext())
{
    // 查詢數(shù)據(jù)
    var data = dbContext.YourEntities.ToList();

    // 插入數(shù)據(jù)
    var newEntity = new YourEntity { Property1 = value1, Property2 = value2 };
    dbContext.YourEntities.Add(newEntity);
    dbContext.SaveChanges();

    // 更新數(shù)據(jù)
    var entityToUpdate = dbContext.YourEntities.Find(id);
    entityToUpdate.Property1 = newValue;
    dbContext.SaveChanges();

    // 刪除數(shù)據(jù)
    var entityToDelete = dbContext.YourEntities.Find(id);
    dbContext.YourEntities.Remove(entityToDelete);
    dbContext.SaveChanges();
}

這是連接 SQL Server 數(shù)據(jù)庫的兩種常用方法,具體使用哪種取決于項目的需求和復(fù)雜度。

0