在 ADO.NET 數據訪問中,SqlCommand 與 SqlDataAdapter 是兩大核心類,功能定位截然不同。本文釐清二者區別,指導選型。
| 特性 | SqlCommand | SqlDataAdapter |
|---|---|---|
| 定位 | 執行單條 SQL/預存過程(增刪改查) | 數據集與數據庫的橋樑,批量填充/更新 DataSet/DataTable |
| 連接管理 | 手動 Open/Close | 內部自動管理連接(Fill/Update 時自動打開關閉) |
| 返回結果 | ExecuteReader/ExecuteScalar/ExecuteNonQuery | Fill 返回 DataTable/DataSet,適合離線數據操作 |
| 適用場景 | 單次查詢、執行 DDL/DML、輸出參數 | WinForms/WPF 數據綁定、離線編輯、批量同步 |
DataGridView、GridView 等控件。Update() 批量寫回數據庫。// SqlCommand 單次查詢
using (var cmd = new SqlCommand("SELECT * FROM Users", conn)) {
using (var reader = cmd.ExecuteReader()) {
while (reader.Read()) { /* 逐行處理 */ }
}
}
// SqlDataAdapter 填充 DataTable 並綁定
var adapter = new SqlDataAdapter("SELECT * FROM Users", conn);
var dt = new DataTable();
adapter.Fill(dt);
dataGridView1.DataSource = dt;
簡單說:命令用於執行,適配器用於填充與同步。按業務選型,避免濫用。