一个有趣的问题,你知道SqlDataAdapter中的Fill是怎么实现的吗

2023年 10月 8日 45.9k 0

一、背景

讲故事

最近因为各方面原因换了一份工作,去了一家主营物联柜的公司,有意思的是物联柜上的终端是用 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, " %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

相关文章

Oracle如何使用授予和撤销权限的语法和示例
Awesome Project: 探索 MatrixOrigin 云原生分布式数据库
下载丨66页PDF,云和恩墨技术通讯(2024年7月刊)
社区版oceanbase安装
Oracle 导出CSV工具-sqluldr2
ETL数据集成丨快速将MySQL数据迁移至Doris数据库

发布评论