核心特性
- 離線架構:
Fill() 完成後,DataSet 與資料庫連線完全斷開,適合多層架構傳遞資料實體。
- 命令封裝:內含
SelectCommand、InsertCommand、UpdateCommand、DeleteCommand 四大命令,支援批次更新回寫。
- 對應靈活:
TableMappings 可將資料庫表名映射為自訂 DataTable 名稱。
三種常見建構模式
模式一:手動組裝命令物件(最靈活)
string connStr = "Server=.;Database=Northwind;Integrated Security=true;";
string sql = "SELECT CustomerID, CompanyName, City FROM Customers";
using (SqlConnection cn = new SqlConnection(connStr))
using (SqlCommand cmd = new SqlCommand(sql, cn))
using (SqlDataAdapter da = new SqlDataAdapter()) {
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds); // ds.Tables[0] 名稱為 "Table"
}
模式二:建構子直接傳入 SQL + 連線字串(最簡潔)
string connStr = "Server=.;Database=Northwind;Integrated Security=true;";
string sql = "SELECT * FROM Customers";
using (SqlDataAdapter da = new SqlDataAdapter(sql, connStr)) {
DataSet ds = new DataSet();
da.Fill(ds);
}
模式三:建構子傳入 SQL + SqlConnection 物件(連線池控制)
string connStr = "Server=.;Database=Northwind;Integrated Security=true;";
using (SqlConnection cn = new SqlConnection(connStr))
using (SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Customers", cn)) {
DataSet ds = new DataSet();
da.Fill(ds);
}
Fill 方法進階用法
| 多載 | 用途 |
Fill(DataSet) | 填入預設表名 "Table", "Table1"... |
Fill(DataSet, "Customers") | 指定 DataTable 名稱 |
Fill(DataTable) | 直接填入單一 DataTable,無需 DataSet |
Fill(startRecord, maxRecords, DataTable) | 分頁填入(略過前 N 筆,最多取 M 筆) |
TableMapping 自訂表名
da.TableMappings.Add("Table", "Customers"); // 將預設 "Table" 映射為 "Customers"
da.Fill(ds); // ds.Tables["Customers"] 可直接存取
更新回寫資料庫
// 需預先設定 Insert/Update/DeleteCommand(可用 SqlCommandBuilder 自動產生)
SqlCommandBuilder cb = new SqlCommandBuilder(da);
// 修改 DataSet 內容...
da.Update(ds); // 批次執行對應命令
最佳實務提醒
using 區塊確保連線、命令、配接器正確釋放。
- 大量資料(> 10 萬列)建議改用
SqlBulkCopy 或資料流處理,避免記憶體壓力。
Fill 會隱式開啟/關閉連線;若連線已開啟則保持開啟狀態。