一個有趣的問題, 你知道SqlDataAdapter中的Fill是怎麼實現的嗎

来源:https://www.cnblogs.com/huangxincheng/archive/2020/07/22/13358901.html
-Advertisement-
Play Games

一:背景 1. 講故事 最近因為各方面原因換了一份工作,去了一家主營物聯櫃的公司,有意思的是物聯柜上的終端是用 wpf 寫的,代碼也算是年久失修,感覺技術債還是蠻重的,前幾天在調試一個bug的時候,看到了一段類似這樣的代碼: var dt = new DataTable(); SqlDataAdap ...


一:背景

1. 講故事

最近因為各方面原因換了一份工作,去了一家主營物聯櫃的公司,有意思的是物聯柜上的終端是用 wpf 寫的,代碼也算是年久失修,感覺技術債還是蠻重的,前幾天在調試一個bug的時候,看到了一段類似這樣的代碼:


    var dt = new DataTable();
    SqlDataAdapter adapter = new SqlDataAdapter(new SqlCommand());
    adapter.Fill(dt);

是不是很眼熟哈,或許你也已經多年不見了,猶記得那時候為了能從資料庫獲取數據,第一種方法就是採用 SqlDataReader 一行一行從資料庫讀取,而且還要操心 Reader 的 close 問題,第二種方法為了避免麻煩,就直接使用了本篇說到的 SqlDataAdapter ,簡單粗暴,啥也不用操心,對了,不知道您是否和我一樣對這個 Fill 方法很好奇呢?,它是如何將數據塞入到 DataTable 中的呢? 也是用的 SqlDataReader 嗎? 而且 Fill 還有好幾個擴展方法,哈哈,本篇就逐個聊一聊,就當回顧經典啦!

二:對Fill方法的探究

1. 使用 dnspy 查看Fill源碼

dnspy小工具大家可以到GitHub上面去下載一下,這裡就不具體說啦,接下來追一下Fill的最上層實現,如下代碼:


		public int Fill(DataTable dataTable)
		{
			IntPtr intPtr;
			Bid.ScopeEnter(out intPtr, "<comm.DbDataAdapter.Fill|API> %d#, dataTable\n", base.ObjectID);
			int result;
			try
			{
				DataTable[] dataTables = new DataTable[]
				{
					dataTable
				};
				IDbCommand selectCommand = this._IDbDataAdapter.SelectCommand;
				CommandBehavior fillCommandBehavior = this.FillCommandBehavior;
				result = this.Fill(dataTables, 0, 0, selectCommand, fillCommandBehavior);
			}
			finally
			{
				Bid.ScopeLeave(ref intPtr);
			}
			return result;
		}


上面的代碼比較關鍵的一個地方就是 IDbCommand selectCommand = this._IDbDataAdapter.SelectCommand; 這裡的 SelectCommand 來自於哪裡呢? 來自於你 new SqlDataAdapter 的時候塞入的構造函數 SqlCommand,如下代碼:


		public SqlDataAdapter(SqlCommand selectCommand) : this()
		{
			this.SelectCommand = selectCommand;
		}

然後繼續往下看 this.Fill 方法,代碼簡化後如下:


		protected virtual int Fill(DataTable[] dataTables, int startRecord, int maxRecords, IDbCommand command, CommandBehavior behavior)
		{
            result = this.FillInternal(null, dataTables, startRecord, maxRecords, null, command, behavior);
			
			return result;
		}

上面這段代碼沒啥好說的,繼續往下追蹤 this.FillInternal 方法,簡化後如下:


		private int FillInternal(DataSet dataset, DataTable[] datatables, int startRecord, int maxRecords, string srcTable, IDbCommand command, CommandBehavior behavior)
		{
			int result = 0;
			try
			{
				IDbConnection connection = DbDataAdapter.GetConnection3(this, command, "Fill");
				try
				{
					IDataReader dataReader = null;
					try
					{
						dataReader = command.ExecuteReader(behavior);
						result = this.Fill(datatables, dataReader, startRecord, maxRecords);
					}
					finally
					{
						if (dataReader != null)	dataReader.Dispose();
					}
				}
				finally
				{
					DbDataAdapter.QuietClose(connection, originalState);
				}
			}
			finally
			{
				if (flag)
				{
					command.Transaction = null;
					command.Connection = null;
				}
			}
			return result;
		}

大家可以仔細研讀一下上面的代碼,挺有意思的,至少你可以獲取以下兩點信息:

  • 從各個 finally 中可以看到,當數據 fill 到 datatable 中之後,操作資料庫的幾大對象 Connection,Transaction,DataReader 都會進行關閉,你根本不需要操心。

  • this.Fill(datatables, dataReader, startRecord, maxRecords) 中可以看到,底層不出意外也是通過 dataReader.read() 一行一行讀取然後塞到 DataTable中去的,不然它拿這個 dataReader 幹嘛呢? 不信的話可以繼續往下追。


		protected virtual int Fill(DataTable[] dataTables, IDataReader dataReader, int startRecord, int maxRecords)
		{
			try
			{
				int num = 0;
				bool flag = false;
				DataSet dataSet = dataTables[0].DataSet;
				int num2 = 0;
				while (num2 < dataTables.Length && !dataReader.IsClosed)
				{
					DataReaderContainer dataReaderContainer = DataReaderContainer.Create(dataReader, this.ReturnProviderSpecificTypes);
					if (num2 == 0)
					{
						bool flag2;
						do
						{
							flag2 = this.FillNextResult(dataReaderContainer);
						}
						while (flag2 && dataReaderContainer.FieldCount <= 0);	
						}
					}
				result = num;
			}
			return result;
		}

從上面代碼可以看到, dataReader 被封裝到了 DataReaderContainer 中,用 FillNextResult 判斷是否還有批語句sql,從而方便生成多個 datatable 對象,最後就是填充 DataTable ,當然就是用 dataReader.Read()啦,不信你可以一直往裡面追嘛,如下代碼:


		private int FillLoadDataRow(SchemaMapping mapping)
		{
			int num = 0;
			DataReaderContainer dataReader = mapping.DataReader;
			
			while (dataReader.Read())
			{
				mapping.LoadDataRow();
				num++;
			}
			return num;
		}

到這裡你應該意識到: DataReader 的性能肯定比 Fill 到 DataTable 要高的太多,所以它和靈活性兩者之間看您取捨了哈。

二:Fill 的其他重載方法

剛纔給大家介紹的是帶有 DataTable 參數的重載,其實除了這個還有另外四種重載方法,如下圖:


	public override int Fill(DataSet dataSet);
	public int Fill(DataSet dataSet, string srcTable);
	public int Fill(DataSet dataSet, int startRecord, int maxRecords, string srcTable);
	public int Fill(int startRecord, int maxRecords, params DataTable[] dataTables);

1. startRecord 和 maxRecords

從字面意思看就是想從指定的位置 (startRecord) 開始讀,然後最多讀取 maxRecords 條記錄,很好理解,我們知道 reader() 是只讀向前的,然後一起看一下源碼底層是怎麼實現的。

從上圖中可以看出,還是很簡單的哈,踢掉 startRecord 個 reader(),然後再只讀向前獲取最多 maxRecords 條記錄。

2. dataSet 和 srcTable

這裡的 srcTable 是什麼意思呢? 從 vs 中看是這樣的: The name of the source table to use for table mapping. 乍一看也不是特別清楚,沒關係,我們直接看源碼就好啦,反正我也沒測試,嘿嘿。

從上圖中你應該明白大概意思就是給你 dataset 中的 datatable 取名字,比如:name= 學生表, 那麼database中的的 tablename依次是: 學生表,學生表1,學生表2 ..., 這樣你就可以索引獲取表的名字了哈,如下代碼所示:

        DataSet dataSet = new DataSet();
        dataSet.Tables.Add(new DataTable("學生表"));
        var tb = dataSet.Tables["學生表"];

四:總結

本篇就聊這麼多吧,算是解了多年之前我的一個好奇心,希望本篇對您有幫助。

如您有更多問題與我互動,掃描下方進來吧~

圖片名稱
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1.首先使用VS創建WebAPI項目 (這裡有個幫助類,將此幫助類複製到項目里,有興趣可以學著寫) //文件上傳下載,導入導出輔助類 public class APIFileHelp { //此為限制文件格式 public string[] ExtentsfileName = new string[ ...
  • 今天總結一下 關於XML字元串轉DataTable 方法: 引用:using System.Xml; using Newtonsoft.Json;using System.Data; using System.Collections; 首先,定義一個xml字元串來接收傳過來的數據, string x ...
  • 今天總結一下關於DataTable,XML轉JSON的方法: 首先需要引入命名空間: using Newtonsoft.Json 1 public string DataTableToJsonWithStringBuilder(DataTable table) 2 { 3 var jsonStrin ...
  • 最近在做調用第三方介面,要求入參AES加密,並且秘鑰為16位的長度,在此記錄一下。 首先引用命名空間: using System.IO; using System.Text; using System.Security.Cryptography; 1 /// <summary> 2 /// AES加 ...
  • 上篇我們完成了數據源列表展示功能(還未測試)。 本篇我們來新增數據源,並查看列表展示功能。 接上篇: 二、數據源管理功能開發 2、新增數據源 我們用模態對話框來完成數據源的新增,效果如下圖: 我們分兩部分講解:展示 和 邏輯。 展示: 我們用的前端UI是基於bootstrap的,因此bootstra ...
  • Tips:本篇已加入系列文章閱讀目錄,可點擊查看更多相關文章。 前言 Docker 是一個開源的應用容器引擎,它十分火熱,如今幾乎成為了後端開發人員必須掌握的一項技能。即使你在生產環境中可能用不上它,就算把它當作一個輔助開發的工具來使用,也是非常方便的。本文就介紹一下.Net Core應用在Dock ...
  • 1.原因 載入的時候沒有調取 AssemblyLoadContext.Default 2.解決方案: 在程式啟動的時候,手動調用 /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class ...
  • 天天寫,不一定就明白。 又及,前兩天看了一個關於同步方法中調用非同步方法的文章,裡面有些概念不太正確,所以整理了這個文章。 一、同步和非同步。 先說同步。 同步概念大家都很熟悉。在非同步概念出來之前,我們的代碼都是按同步的方式寫的。簡單來說,就是程式嚴格按照代碼的邏輯次序,一行一行執行。 看一段代碼: p ...
一周排行
    -Advertisement-
    Play Games
  • 前言 在我們開發過程中基本上不可或缺的用到一些敏感機密數據,比如SQL伺服器的連接串或者是OAuth2的Secret等,這些敏感數據在代碼中是不太安全的,我們不應該在源代碼中存儲密碼和其他的敏感數據,一種推薦的方式是通過Asp.Net Core的機密管理器。 機密管理器 在 ASP.NET Core ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 順序棧的介面程式 目錄順序棧的介面程式頭文件創建順序棧入棧出棧利用棧將10進位轉16進位數驗證 頭文件 #include <stdio.h> #include <stdbool.h> #include <stdlib.h> 創建順序棧 // 指的是順序棧中的元素的數據類型,用戶可以根據需要進行修改 ...
  • 前言 整理這個官方翻譯的系列,原因是網上大部分的 tomcat 版本比較舊,此版本為 v11 最新的版本。 開源項目 從零手寫實現 tomcat minicat 別稱【嗅虎】心有猛虎,輕嗅薔薇。 系列文章 web server apache tomcat11-01-官方文檔入門介紹 web serv ...
  • C總結與剖析:關鍵字篇 -- <<C語言深度解剖>> 目錄C總結與剖析:關鍵字篇 -- <<C語言深度解剖>>程式的本質:二進位文件變數1.變數:記憶體上的某個位置開闢的空間2.變數的初始化3.為什麼要有變數4.局部變數與全局變數5.變數的大小由類型決定6.任何一個變數,記憶體賦值都是從低地址開始往高地 ...
  • 如果讓你來做一個有狀態流式應用的故障恢復,你會如何來做呢? 單機和多機會遇到什麼不同的問題? Flink Checkpoint 是做什麼用的?原理是什麼? ...
  • C++ 多級繼承 多級繼承是一種面向對象編程(OOP)特性,允許一個類從多個基類繼承屬性和方法。它使代碼更易於組織和維護,並促進代碼重用。 多級繼承的語法 在 C++ 中,使用 : 符號來指定繼承關係。多級繼承的語法如下: class DerivedClass : public BaseClass1 ...
  • 前言 什麼是SpringCloud? Spring Cloud 是一系列框架的有序集合,它利用 Spring Boot 的開發便利性簡化了分散式系統的開發,比如服務註冊、服務發現、網關、路由、鏈路追蹤等。Spring Cloud 並不是重覆造輪子,而是將市面上開發得比較好的模塊集成進去,進行封裝,從 ...
  • class_template 類模板和函數模板的定義和使用類似,我們已經進行了介紹。有時,有兩個或多個類,其功能是相同的,僅僅是數據類型不同。類模板用於實現類所需數據的類型參數化 template<class NameType, class AgeType> class Person { publi ...
  • 目錄system v IPC簡介共用記憶體需要用到的函數介面shmget函數--獲取對象IDshmat函數--獲得映射空間shmctl函數--釋放資源共用記憶體實現思路註意 system v IPC簡介 消息隊列、共用記憶體和信號量統稱為system v IPC(進程間通信機制),V是羅馬數字5,是UNI ...