首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

ADO.NET 核心物件速查手冊:Connection、Command、DataReader、DataAdapter、DataSet 全解析

     編輯:更多程式設計知識

ADO.NET 核心物件模型精要整理,涵蓋連接建立、命令執行、資料讀取、離線資料集操作五大板塊,附完整代碼範例與多載方法表,適合速查與入門夯實。

一、SqlConnection 連接 SQL Server

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();

二、OleDbConnection 通用連接

  • SQL Server:Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=test;Integrated Security=SSPI
  • Access:Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\db.mdb
  • Oracle:Provider=MSDAORA;Data Source=db;user id=sa;password=xxx

三、SqlCommand 四種建構子與執行方法

建構子用途
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 唯前唯讀高速串流

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 離線資料橋樑

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 來源。

六、DataSet 離線資料容器

  • DataTableCollection Tables:ds.Tables["Name"] 存取
  • DataTable.Select(filter, sort, viewState):動態篩選排序
  • DataView:new DataView(table, "id>5", "name DESC", DataViewRowState.CurrentRows) 索引加速查詢

七、關鍵屬性速查

物件關鍵屬性/方法
DataColumnDataType, AllowDBNull, AutoIncrement, MaxLength, ReadOnly
DataRowItem[col], RowState, HasErrors, AcceptChanges/RejectChanges
DataTablePrimaryKey, Rows, Columns, Constraints, Select(), NewRow()
DataSetTables, Relations, ReadXml/WriteXml, Merge(), GetChanges()
DataViewSort, RowFilter, RowStateFilter, Find/FindRows, ToTable()
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved