ADO.NET 核心物件模型精要整理,涵蓋連接建立、命令執行、資料讀取、離線資料集操作五大板塊,附完整代碼範例與多載方法表,適合速查與入門夯實。
using System.Data.SqlClient;
string connStr = "user id=sa;password=xxx;database=test;server=127.0.0.1;Connect Timeout=30";
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=test;Integrated Security=SSPIProvider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\db.mdbProvider=MSDAORA;Data Source=db;user id=sa;password=xxx| 建構子 | 用途 |
|---|---|
SqlCommand() | 空命令,後續設定屬性 |
SqlCommand(sqlText) | 指定查詢文本 |
SqlCommand(sqlText, connection) | 文本+連接 |
SqlCommand(sqlText, connection, transaction) | 文本+連接+事務 |
關聯連接:cmd.Connection = conn 或 cmd = conn.CreateCommand()
四大執行方法:
ExecuteReader() → SqlDataReader(多行)ExecuteNonQuery() → int 影響行數(INSERT/UPDATE/DELETE)ExecuteScalar() → object 單值(聚合函數)ExecuteXmlReader() → XmlReader(FOR XML 結果)SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
Console.WriteLine($"{dr.GetInt32(0)} {dr.GetString(1)}");
// 或 dr[0], dr["colName"], dr.GetDateTime(2) 等型別化存取器
}
dr.Close();
進階:NextResult() 處理多結果集;GetSchemaTable() 取中繼資料;CommandBehavior.CloseConnection 自動關連接。
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Users", conn);
// 或 da.SelectCommand = new SqlCommand(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds, "Users"); // 自動開關連接
Fill 多載:支援 DataSet/DataTable、起始/最大筆數、IDataReader 來源。
DataTableCollection Tables:ds.Tables["Name"] 存取DataTable.Select(filter, sort, viewState):動態篩選排序DataView:new DataView(table, "id>5", "name DESC", DataViewRowState.CurrentRows) 索引加速查詢| 物件 | 關鍵屬性/方法 |
|---|---|
| DataColumn | DataType, AllowDBNull, AutoIncrement, MaxLength, ReadOnly |
| DataRow | Item[col], RowState, HasErrors, AcceptChanges/RejectChanges |
| DataTable | PrimaryKey, Rows, Columns, Constraints, Select(), NewRow() |
| DataSet | Tables, Relations, ReadXml/WriteXml, Merge(), GetChanges() |
| DataView | Sort, RowFilter, RowStateFilter, Find/FindRows, ToTable() |