C#和SQL Server連接常用通訊方式

C#和SQL Server連接通訊

在 C# 中與 SQL Server 建立數據庫連接,主要通過 ADO.NET 技術實現。以下是幾種常見的連接方式及相關實踐:

ADO.NET 全面指南:C# 數據庫訪問核心技術

ADO.NET 是 .NET Framework 中用于數據訪問的核心組件,提供了一套強大的類庫,使應用程序能夠連接各種數據源(如 SQL Server、Oracle、MySQL 等)并與之交互。
圖片展示
在這里插入圖片描述
腳本代碼

graph TDA[應用程序] --> B[數據提供程序]B --> C[SQL Server]B --> D[Oracle]B --> E[OLE DB]B --> F[ODBC]B --> G[其他數據源]subgraph ADO.NET 組件H[Connection] --> I[Command]I --> J[DataReader]I --> K[DataAdapter]K --> L[DataSet]L --> M[DataTable]L --> N[DataRelation]endA --> H

主要組件詳解

1. 數據提供程序 (Data Providers)

  • SQL Server 提供程序System.Data.SqlClient
  • OLE DB 提供程序System.Data.OleDb
  • ODBC 提供程序System.Data.Odbc
  • Oracle 提供程序System.Data.OracleClient

2. 核心對象

  • SqlConnection:管理與數據庫的連接
  • SqlCommand:執行 SQL 語句或存儲過程
  • SqlDataReader:提供高性能的只進只讀數據流
  • SqlDataAdapter:在 DataSet 和數據庫之間架起橋梁
  • DataSet:內存中的數據庫表示(斷開式數據訪問)
  • DataTable:表示內存中的數據表

連接模式 vs 斷開模式

連接模式 (使用 DataReader)

using (SqlConnection connection = new SqlConnection(connectionString))
{connection.Open();string sql = "SELECT * FROM Products WHERE Price > @minPrice";using (SqlCommand command = new SqlCommand(sql, connection)){command.Parameters.AddWithValue("@minPrice", 50.00);using (SqlDataReader reader = command.ExecuteReader()){while (reader.Read()){Console.WriteLine($"Product: {reader["ProductName"]}, Price: {reader["Price"]}");}}}
}

斷開模式 (使用 DataSet/DataAdapter)

using (SqlConnection connection = new SqlConnection(connectionString))
{SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Customers", connection);DataSet dataSet = new DataSet();// 填充 DataSetadapter.Fill(dataSet, "Customers");// 處理數據(無需保持連接)DataTable customersTable = dataSet.Tables["Customers"];foreach (DataRow row in customersTable.Rows){Console.WriteLine($"Customer: {row["FirstName"]} {row["LastName"]}");}// 更新數據DataRow newRow = customersTable.NewRow();newRow["FirstName"] = "John";newRow["LastName"] = "Doe";customersTable.Rows.Add(newRow);// 將更改同步回數據庫SqlCommandBuilder builder = new SqlCommandBuilder(adapter);adapter.Update(dataSet, "Customers");
}

關鍵操作詳解

1. 參數化查詢(防止 SQL 注入)

using (SqlCommand cmd = new SqlCommand("INSERT INTO Users (Username, Email) VALUES (@username, @email)", connection))
{cmd.Parameters.Add("@username", SqlDbType.NVarChar, 50).Value = username;cmd.Parameters.Add("@email", SqlDbType.NVarChar, 100).Value = email;cmd.ExecuteNonQuery();
}

2. 執行存儲過程

using (SqlCommand cmd = new SqlCommand("GetCustomerOrders", connection))
{cmd.CommandType = CommandType.StoredProcedure;cmd.Parameters.AddWithValue("@CustomerID", customerId);using (SqlDataReader reader = cmd.ExecuteReader()){// 處理結果}
}

3. 事務處理

using (SqlConnection connection = new SqlConnection(connectionString))
{connection.Open();SqlTransaction transaction = connection.BeginTransaction();try{using (SqlCommand cmd1 = new SqlCommand("UPDATE Account SET Balance = Balance - 100 WHERE ID = 1", connection, transaction))using (SqlCommand cmd2 = new SqlCommand("UPDATE Account SET Balance = Balance + 100 WHERE ID = 2", connection, transaction)){cmd1.ExecuteNonQuery();cmd2.ExecuteNonQuery();transaction.Commit();Console.WriteLine("Transaction completed successfully.");}}catch (Exception ex){transaction.Rollback();Console.WriteLine($"Transaction rolled back: {ex.Message}");}
}

4. 異步操作

public async Task<List<Product>> GetProductsAsync()
{var products = new List<Product>();using (SqlConnection connection = new SqlConnection(connectionString)){await connection.OpenAsync();string sql = "SELECT ProductID, ProductName, UnitPrice FROM Products";using (SqlCommand command = new SqlCommand(sql, connection)){using (SqlDataReader reader = await command.ExecuteReaderAsync()){while (await reader.ReadAsync()){products.Add(new Product{ProductID = reader.GetInt32(0),ProductName = reader.GetString(1),UnitPrice = reader.GetDecimal(2)});}}}}return products;
}

最佳實踐

  1. 資源管理:始終使用 using 語句確保對象正確釋放
  2. 連接管理:保持連接打開時間最短
  3. 參數化查詢:防止 SQL 注入攻擊
  4. 錯誤處理:使用 try-catch 塊處理數據庫異常
  5. 連接池:利用 ADO.NET 內置的連接池機制
  6. 異步操作:在 I/O 密集型操作中使用異步方法
  7. 安全存儲:將連接字符串存儲在配置文件中
  8. 類型安全:使用 GetInt32(), GetString() 等方法而非索引器

ADO.NET vs Entity Framework

特性ADO.NETEntity Framework
抽象級別低級別,直接 SQL 操作高級別,面向對象
性能更高(直接控制)良好(有優化空間)
開發速度較慢更快(自動代碼生成)
復雜性需要更多代碼簡化數據訪問
適用場景高性能需求、復雜查詢快速開發、ORM 需求
學習曲線陡峭(需了解 SQL)較平緩(面向對象)

ADO.NET 核心組件架構

1. 使用 SqlConnection 直接連接

核心命名空間System.Data.SqlClient
基礎步驟

using System.Data.SqlClient;string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";using (SqlConnection connection = new SqlConnection(connectionString))
{connection.Open();// 執行數據庫操作(如 SqlCommand)using (SqlCommand cmd = new SqlCommand("SELECT * FROM Table", connection)){SqlDataReader reader = cmd.ExecuteReader();while (reader.Read()){// 處理數據}}
} // 自動關閉連接

2. 使用連接字符串構建器(SqlConnectionStringBuilder)

優勢:避免連接字符串拼寫錯誤,支持強類型屬性。

var builder = new SqlConnectionStringBuilder();
builder.DataSource = "localhost";
builder.InitialCatalog = "MyDatabase";
builder.UserID = "sa";
builder.Password = "securePassword";
builder.IntegratedSecurity = false; // 使用 SQL 身份驗證
builder.ConnectTimeout = 30; // 連接超時時間(秒)using (SqlConnection conn = new SqlConnection(builder.ConnectionString))
{conn.Open();// ... 操作數據庫
}

3. Windows 身份驗證(集成安全)

適用場景:使用當前 Windows 用戶憑據連接。

string connectionString = "Server=localhost;Database=MyDB;Integrated Security=True;";using (SqlConnection conn = new SqlConnection(connectionString))
{conn.Open();// ... 操作
}

4. 異步連接(Async/Await)

適用場景:避免阻塞 UI 線程,提高并發性能。

using (SqlConnection conn = new SqlConnection(connectionString))
{await conn.OpenAsync(); // 異步打開連接using (SqlCommand cmd = new SqlCommand("SELECT * FROM Table", conn)){using (SqlDataReader reader = await cmd.ExecuteReaderAsync()){while (await reader.ReadAsync()){// 異步讀取數據}}}
}

5. 從配置文件讀取連接字符串

步驟

App.config / Web.config 中添加配置:

<configuration><connectionStrings><add name="MyDB" connectionString="Server=.;Database=MyDB;Integrated Security=True;" providerName="System.Data.SqlClient"/></connectionStrings>
</configuration>

C# 代碼中讀取

using System.Configuration;string connStr = ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connStr))
{// ...
}

6. 依賴注入(DI)方式

適用場景:ASP.NET Core 等現代框架。

// Startup.cs 中注冊服務
services.AddScoped(_ => new SqlConnection(Configuration.GetConnectionString("DefaultConnection")));// 在 Controller 或 Service 中注入
public class MyService
{private readonly SqlConnection _connection;public MyService(SqlConnection connection){_connection = connection;}public async Task GetData(){await _connection.OpenAsync();// ... 操作}
}

7. 連接池優化

默認啟用:ADO.NET 自動管理連接池。
關鍵參數

  • Max Pool Size:最大連接數(默認 100)
  • Min Pool Size:最小保留連接數(默認 0)
  • Pooling=True:啟用連接池(默認 true)

示例

string connStr = "Server=.;Database=MyDB;Integrated Security=True;Max Pool Size=200;";

8. 使用 Entity Framework Core(ORM 方式)

非直接連接:通過 DbContext 抽象連接。

// 定義 DbContext
public class AppDbContext : DbContext
{protected override void OnConfiguring(DbContextOptionsBuilder options)=> options.UseSqlServer("Server=.;Database=MyDB;Integrated Security=True;");
}// 使用示例
using (var context = new AppDbContext())
{var users = context.Users.ToList(); // 自動管理連接
}

連接字符串關鍵參數說明

參數說明
Server / Data Source服務器地址(如 localhost, ., 192.168.1.10
Database / Initial Catalog數據庫名
User IdSQL 身份驗證用戶名
PasswordSQL 身份驗證密碼
Integrated Security是否使用 Windows 身份驗證(true/falseSSPI
Connection Timeout連接超時時間(秒,默認 15)
Encrypt是否加密連接(推薦 true,配合 TrustServerCertificate 使用)

最佳實踐

  1. 始終使用 using 語句:確保連接及時關閉。

  2. 敏感信息保護:連接字符串避免硬編碼,使用配置文件或密鑰管理服務。

  3. 異步操作:高并發場景使用 OpenAsync()ExecuteReaderAsync()

  4. 錯誤處理:用 try-catch 捕獲 SqlException

  5. 連接池監控:通過性能計數器(如 NumberOfActiveConnectionPools)優化連接池。

    | 連接超時時間(秒,默認 15) |
    | Encrypt | 是否加密連接(推薦 true,配合 TrustServerCertificate 使用) |

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/87940.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/87940.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/87940.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

安卓10.0系統修改定制化____實現自動開啟 USB 調試?的步驟解析 列舉常用的幾種修改方法

對于安卓開發者、測試人員,甚至是喜歡折騰手機的數碼愛好者來說,USB 調試是一個非常重要的功能。它能讓手機與電腦相連,實現應用安裝、系統調試、數據傳輸等操作。但每次連接手機都要手動去設置里開啟 USB 調試,實在麻煩。其實,通過修改安卓 10.0 的 ROM,就能讓手機自動開…

Redisson詳細教程 - 從入門到精通

目錄 1. 什么是Redisson 2. 為什么要用Redisson 3. 環境準備和配置 4. 基礎使用方法 5. 分布式數據結構 6. 分布式鎖詳解 7. 分布式服務 8. 實際應用場景 9. 最佳實踐 10. 常見問題解答 總結 1. 什么是Redisson 簡單理解 想象一下,Redis就像一個超級強大的"內…

動態規劃VS記憶化搜索(2)

luoguP1434滑雪 題目描述 Michael 喜歡滑雪。這并不奇怪&#xff0c;因為滑雪的確很刺激。可是為了獲得速度&#xff0c;滑的區域必須向下傾斜&#xff0c;而且當你滑到坡底&#xff0c;你不得不再次走上坡或者等待升降機來載你。Michael 想知道在一個區域中最長的滑坡。區域由…

如何將服務守護進程化

進程組 什么是進程組 之前我們提到了進程的概念&#xff0c; 其實每一個進程除了有一個進程 ID(PID)之外 還屬于一個進程組。進程組是一個或者多個進程的集合&#xff0c; 一個進程組可以包含多個進程。 每一個進程組也有一個唯一的進程組 ID(PGID)&#xff0c; 并且這個 PGID …

【跟著PMP學習項目管理】項目管理 之 范圍管理知識點

目錄 一、收集需求 1、知識點匯總 2、輸入 3、工具 4、輸出 二、定義范圍 1、知識點匯總 2、輸入 3、工具 4、輸出 三、創作工作分解結構 1、知識點匯總 2、輸入 3、工具 4、輸出 四、核實范圍 1、知識點匯總 2、輸入 3、工具 4、輸出 五、控制范圍 1、知…

AIX 環境磁盤空間管理指南

AIX 環境磁盤空間管理指南 在AIX環境中&#xff0c;磁盤空間的監控、管理與擴展是運維人員必備的技能。本文通過實際案例&#xff0c;系統地介紹如何查詢磁盤信息、卷組(VG)、邏輯卷(LV)信息&#xff0c;以及在磁盤空間不足時的擴容方案&#xff0c;幫助讀者掌握磁盤空間管理的…

k8s將service的IP對應的不同端口分配到不同的pod上

在Kubernetes中&#xff0c;Service是一種抽象層&#xff0c;它將請求路由到一組Pod。當你需要將Service的不同端口映射到不同的Pod時&#xff0c;可以通過以下兩種主要方式實現&#xff1a; 方法一&#xff1a;使用單個Service的多端口配置 如果不同的Pod提供不同的服務&…

aic8800M40低功耗sdio wifi在arm-linux平臺調試經驗

背景 好多年沒有搞過wifi相關的內容了,最近也被安排上了,把一顆低功耗aic8800M40的芯片在arm-linux開發板上做bring up,記錄一下SDIO wifi調試的過程和經驗,SDIO驅動這里需要改動一些linux內核HOST驅動代碼,會在文章中貼出來: AIC8800M40芯片簡介 這個wifi芯片是一顆低…

Redis基礎(1):NoSQL認識

SQL和NoSQL數據庫可以分為關系型數據庫和非關系型數據庫&#xff0c;SQL(Structured Query Language)相信大家并不陌生&#xff0c;這是用于操作關系型數據庫的語言&#xff0c;而NoSQL&#xff0c;顧名思義&#xff0c;它對應的就是非關系數據庫&#xff0c;它是操作非關系型數…

QT6 源(153)模型視圖架構里的表格窗體視圖 QTableWidget 篇三:源碼及其元素 QTableWidgetItem 的源代碼帶注釋

&#xff08;14&#xff09;本源代碼定義于頭文件 qtablewidget . h 頭文件 &#xff1a; #ifndef QTABLEWIDGET_H #define QTABLEWIDGET_H#include <QtWidgets/qtableview.h> #include <QtWidgets/qtwidgetsglobal.h> #include <QtCore/qlist.h> #include …

SSL證書是網絡安全的一把利刃

SSL證書&#xff08;安全套接層證書&#xff0c;現普遍升級為TLS證書&#xff09;確實是網絡安全領域中一把至關重要的“利刃”&#xff0c;它在保護數據傳輸安全、建立用戶信任、防范網絡攻擊等方面發揮著不可替代的作用。以下是其核心價值與作用的詳細分析&#xff1a;一、SS…

Apache 配置文件提權的實戰思考

在 Linux 系統中&#xff0c;如果普通用戶被授予以 sudo 執行 Apache 并加載自定義配置文件的權限&#xff08;如 sudo apache2 -f /home/user/user.conf&#xff09;&#xff0c;那么該權限極可能被濫用為本地提權路徑。 雖然 Apache 默認采用了更嚴格的權限限制機制&#xff…

代碼隨想錄算法訓練營第四十四天|動態規劃part11

1143.最長公共子序列 題目鏈接&#xff1a;1143. 最長公共子序列 - 力扣&#xff08;LeetCode&#xff09; 文章講解:代碼隨想錄 思路&#xff1a; 其實就是求兩個字符串的最長公共子序列的長度 與公共子數組的區別是可以不連續 &#xff0c;順序對就可以 狀態轉移方程不一樣 …

部署mysql

# 環境: 操作系統window11 安裝了vagrant 通過vagrant部署、啟動虛擬機(centos7) # 準備安裝mysql8 # 添加 MySQL 官方 YUM 源 sudo rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-7.noarch.rpm # 安裝 MySQL Server sudo yum install -y mysql-s…

SQL分析與打印-p6spy組件

有性能消耗&#xff0c;只推薦在非生產環境下使用 SpringBoot3MybatisPlushttps://baomidou.com/guides/p6spy/ MyBatis-Plus提供了SQL分析與打印的功能&#xff0c;通過集成p6spy組件&#xff0c;可以方便地輸出SQL語句及其執行時長。本功能適用于MyBatis-Plus 3.1.0及以上版本…

FLUX.1-Kontext 高效訓練 LoRA:釋放大語言模型定制化潛能的完整指南

在人工智能領域&#xff0c;尤其是大型語言模型&#xff08;LLM&#xff09;的應用浪潮中&#xff0c;高效、低成本地定制模型行為已成為關鍵需求。LoRA&#xff08;Low-Rank Adaptation&#xff09;技術以其參數高效、資源節省的特性脫穎而出。而 FLUX.1-Kontext 作為一款創新…

群暉 DS3617xs DSM 6.1.7 解決 PhotoStation 安裝失敗問題 PHP7.0

群暉 DS3617xs DSM 6.1.7 解決 PhotoStation 安裝失敗問題 PHP7.0問題描述解決方案1. 準備所需文件2. 檢查當前 PHP 版本3. 安裝 PHP 版本5. 查詢已安裝好的套件6. 升級 PHP 版本7. 手動安裝套件PhotoStation注意事項總結問題描述 在群暉 DS3617xs DSM 6.1.7-15284 版本中&…

pnpm 升級

pnpm 的安裝源太多了&#xff0c;感覺系統變量都有引入順序。 今天踩坑記錄&#xff1a; pnpm &#xff0c;如果最初用npm 裝的&#xff0c;可以用npm 升級&#xff1b; 如果最初用brew 裝的&#xff0c;得用brew 升級&#xff1b; 如果最初是用corepack 裝的得用corepack 升級…

[C#] WPF - 資源URI

一、組成 1、資源URI總共包括4個部分(當前程序集可以省略前3個)&#xff1a; ①&#xff1a;pack://application:,,, ②&#xff1a;/[程序集名稱] ③&#xff1a;;Component ④&#xff1a;/[資源路徑] 二、舉例 項目結構如下圖所示&#xff1a; 1、MainWindow.xaml 文件…

【Mysql系列】Mysql 多級隔離級別揭秘

目錄 一、什么是隔離級別 1.1、為什么復合操作需要事務&#xff1f; 1.2、事務的 ACID 特性如何保障操作可靠性&#xff1f; 1.3、隔離性通過隔離級別來控制 二、為什么用多級隔離級別 2.1、事務并發執行時可能引發以下問題 2.1.1、臟讀&#xff08;Dirty Read&#xff…