SqlDataReader,SqlDataAdapter与SqlCommand的一点总结.

本文详细解析了SqlDataAdapter与SqlDataReader的工作原理及使用场景。SqlDataReader适用于在线应用,需手动管理连接;SqlDataAdapter用于离线应用,内置连接管理,并通过SqlDataReader填充数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.SqlDataReader,在线应用,需要conn.open(),使用完之后要关闭.

SqlConnection conn = new SqlConnection(connStr);
 //conn.Open();
SqlCommand cmd = new SqlCommand("select top 10 * from tuser", conn);
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
    Console.WriteLine(reader.GetValue(2));
}
这段代码报错:ExecuteReader requires an open and available Connection. The connection's current state is closed.
应该将conn.Open()打开.


2.SqlDataAdapter,离线应用,不需要用conn.open(), 它把这部分功能给封装到自己内部了,不需要你来显式的去调用, 它直接将数据fill到dataset中.

SqlCommand与ADO时代的Command一样,SqlDataAdapter则是ADO.NET中的新事物,它配合DataSet来使用。其实,DataSet就像是驻留在内存中的小数据库,在DataSet中可以有多张DataTable,这些DataTable之间可以相互关联,就像在数据库中表关联一样!SqlDataAdapter的作用就是将数据从数据库中提取出来,放在DataSet中,当DataSet中的数据发生变化时,SqlDataAdapter再将数据库中的数据更新,以保证数据库中的数据和DataSet中的数据是一致的!
用微软顾问的话讲:DataAdapter就像是一把铁锹,它负责把数据从数据库“铲”到DataSet中,或者将数据从DataSet“铲”到数据库中!

调用DataAdapter的Fill方法时, 它会打开到数据库的SqlConnection, 再通过创建一个SqlCommand和调用ExecuteReader的方式来执行命令, 然后, 通过一个隐式士创建的SqlDataReader, 从数据库读取数据, 结束行的读取之后, SqlDataReader和SqlConnection会被关闭.

DefaultView是DataTable类的一个属性。可用DataView类为每个DataTable定义多个视图。


用Reflacter察看一下SqlDataAdapter及其父类的原代码,其方法调用脉络如下:

Fill(DataSet dataSet)->

Fill(dataSet, 0, 0, "Table", selectCommand, fillCommandBehavior)->

FillInternal(dataSet, null, startRecord, maxRecords, srcTable, command, behavior)->

Fill(dataset, srcTable, reader, startRecord, maxRecords)->

Fill(dataset, srcTable, reader, startRecord, maxRecords)->

FillFromReader(dataSet, null, srcTable, container, startRecord, maxRecords, null, null)->

FillLoadDataRow(mapping)->

while (dataReader.Read())

因此个人认为最精髓的一句总结就是:SqlDataAdapter内部获取数据是通过调用SqlDataReader来实现的,而两者都需要使用SqlConnection和SqlCommand。

 

具体Reflacter察看一下SqlDataAdapter及其父类的原代码如下:

2.1 SqlDataAdapter是DbDataAdapter的子类.

public sealed class SqlDataAdapter : DbDataAdapter, IDbDataAdapter, IDataAdapter, ICloneable

2.2 DbDataAdapter是一个抽象类,里面包含了Fill的具体实现.

public abstract class DbDataAdapter : DataAdapter, IDbDataAdapter, IDataAdapter, ICloneable
{
  public override int Fill(DataSet dataSet)
  {
    int num;
    IntPtr ptr;
    Bid.ScopeEnter(out ptr, "<comm.DbDataAdapter.Fill|API> %d#, dataSet\n", base.ObjectID);
    try
    {
        IDbCommand selectCommand = this._IDbDataAdapter.SelectCommand;
        CommandBehavior fillCommandBehavior = this.FillCommandBehavior;
        num = this.Fill(dataSet, 0, 0, "Table", selectCommand, fillCommandBehavior);
    }
    finally
    {
        Bid.ScopeLeave(ref ptr);
    }
    return num;
  }

  protected virtual int Fill(DataSet dataSet, int startRecord, int maxRecords, string srcTable, IDbCommand command, CommandBehavior behavior)
  {
    int num;
    IntPtr ptr;
    Bid.ScopeEnter(out ptr, "<comm.DbDataAdapter.Fill|API> %d#, dataSet, startRecord, maxRecords, srcTable, command, behavior=%d{ds.CommandBehavior}\n", base.ObjectID, (int) behavior);
    try
    {
        if (dataSet == null)
        {
            throw ADP.FillRequires("dataSet");
        }
        if (startRecord < 0)
        {
            throw ADP.InvalidStartRecord("startRecord", startRecord);
        }
        if (maxRecords < 0)
        {
            throw ADP.InvalidMaxRecords("maxRecords", maxRecords);
        }
        if (ADP.IsEmpty(srcTable))
        {
            throw ADP.FillRequiresSourceTableName("srcTable");
        }
        if (command == null)
        {
            throw ADP.MissingSelectCommand("Fill");
        }
        num = this.FillInternal(dataSet, null, startRecord, maxRecords, srcTable, command, behavior);
    }
    finally
    {
        Bid.ScopeLeave(ref ptr);
    }
    return num;
  }

  private int FillInternal(DataSet dataset, DataTable[] datatables, int startRecord, int maxRecords, string srcTable, IDbCommand command, CommandBehavior behavior)
  {
    bool flag = null == command.Connection;
    try
    {
        IDbConnection connection = GetConnection3(this, command, "Fill");
        ConnectionState open = ConnectionState.Open;
        if (MissingSchemaAction.AddWithKey == base.MissingSchemaAction)
        {
            behavior |= CommandBehavior.KeyInfo;
        }
        try
        {
            QuietOpen(connection, out open);
            behavior |= CommandBehavior.SequentialAccess;
            using (IDataReader reader = null)
            {
                reader = command.ExecuteReader(behavior);
                if (datatables != null)
                {
                    return this.Fill(datatables, reader, startRecord, maxRecords);
                }
                return this.Fill(dataset, srcTable, reader, startRecord, maxRecords);
            }
        }
        finally
        {
            QuietClose(connection, open);
        }
    }
    finally
    {
        if (flag)
        {
            command.Transaction = null;
            command.Connection = null;
        }
    }

  protected virtual int Fill(DataSet dataSet, string srcTable, IDataReader dataReader, int startRecord, int maxRecords)
  {
    int num;
    IntPtr ptr;
    Bid.ScopeEnter(out ptr, "<comm.DataAdapter.Fill|API> %d#, dataSet, srcTable, dataReader, startRecord, maxRecords\n", this.ObjectID);
    try
    {
        if (dataSet == null)
        {
            throw ADP.FillRequires("dataSet");
        }
        if (ADP.IsEmpty(srcTable))
        {
            throw ADP.FillRequiresSourceTableName("srcTable");
        }
        if (dataReader == null)
        {
            throw ADP.FillRequires("dataReader");
        }
        if (startRecord < 0)
        {
            throw ADP.InvalidStartRecord("startRecord", startRecord);
        }
        if (maxRecords < 0)
        {
            throw ADP.InvalidMaxRecords("maxRecords", maxRecords);
        }
        if (dataReader.IsClosed)
        {
            return 0;
        }
        DataReaderContainer container = DataReaderContainer.Create(dataReader, this.ReturnProviderSpecificTypes);
        num = this.FillFromReader(dataSet, null, srcTable, container, startRecord, maxRecords, null, null);
    }
    finally
    {
        Bid.ScopeLeave(ref ptr);
    }
    return num;
  }

  internal int FillFromReader(DataSet dataset, DataTable datatable, string srcTable, DataReaderContainer dataReader, int startRecord, int maxRecords, DataColumn parentChapterColumn, object   parentChapterValue)
  {
    int num2 = 0;
    int schemaCount = 0;
    do
    {
        if (0 < dataReader.FieldCount)
        {
            SchemaMapping mapping = this.FillMapping(dataset, datatable, srcTable, dataReader, schemaCount, parentChapterColumn, parentChapterValue);
            schemaCount++;
            if (((mapping != null) && (mapping.DataValues != null)) && (mapping.DataTable != null))
            {
                mapping.DataTable.BeginLoadData();
                try
                {
                    if ((1 == schemaCount) && ((0 < startRecord) || (0 < maxRecords)))
                    {
                        num2 = this.FillLoadDataRowChunk(mapping, startRecord, maxRecords);
                    }
                    else
                    {
                        int num3 = this.FillLoadDataRow(mapping);
                        if (1 == schemaCount)
                        {
                            num2 = num3;
                        }
                    }
                }
                finally
                {
                    mapping.DataTable.EndLoadData();
                }
                if (datatable != null)
                {
                    return num2;
                }
            }
        }
    }
    while (this.FillNextResult(dataReader));
    return num2;
  }

  private int FillLoadDataRow(SchemaMapping mapping)
  {
    int num = 0;
    DataReaderContainer dataReader = mapping.DataReader;
    if (!this._hasFillErrorHandler)
    {
        while (dataReader.Read())
        {
            mapping.LoadDataRow();
            num++;
        }
        return num;
    }
    while (dataReader.Read())
    {
        try
        {
            mapping.LoadDataRowWithClear();
            num++;
            continue;
        }
        catch (Exception exception)
        {
            if (!ADP.IsCatchableExceptionType(exception))
            {
                throw;
            }
            ADP.TraceExceptionForCapture(exception);
            this.OnFillErrorHandler(exception, mapping.DataTable, mapping.DataValues);
            continue;
        }
    }
    return num;
  }

}

 

using System; using System.Collections; using System.Data; using System.Data.SqlClient; namespace RxjhServer.DbClss { public class DBA { public static void serlog(string txt) { string sqlJl = World.SqlJl; if (sqlJl.Length == 0) { return; } string text = sqlJl; char[] separator = new char[1] { '|' }; string[] array = text.Split(separator); string[] array2 = array; string[] array3 = array2; foreach (string text2 in array3) { if (txt.ToLower().IndexOf(text2.ToLower()) != -1) { Form1.WriteLine(99, txt); } } } public static void serlog(string txt, SqlParameter[] prams) { string sqlJl = World.SqlJl; if (sqlJl.Length == 0) { return; } string[] array = sqlJl.Split('|'); for (int i = 0; i < array.Length; i++) { if (txt.ToLower().IndexOf(array[i].ToLower()) != -1) { Form1.WriteLine(99, txt); } } for (int j = 0; j < array.Length; j++) { foreach (SqlParameter sqlParameter in prams) { if (sqlParameter.SqlValue.ToString().ToLower().IndexOf(array[j].ToLower()) != -1) { Form1.WriteLine(99, txt + " " + sqlParameter.SqlValue.ToString()); } } } } public static void Setlog(string txt, SqlParameter[] prams, Exception ex) { Form1.WriteLine(100, "-----------DBA数据层_错误-----------"); Form1.WriteLine(100, txt); if (prams != null) { foreach (SqlParameter sqlParameter in prams) { Form1.WriteLine(100, sqlParameter.SqlValue.ToString()); } } Form1.WriteLine(100, ex.Message); } public static string getstrConnection(string db) { try { if (db == null) { db = "GameServer"; } World.sql = (World.Db.TryGetValue(db, out var value) ? value.SqlConnect : null); DbClass value2; return World.Db.TryGetValue(db, out value2) ? value2.SqlConnect : null; } catch { return null; } } public static int ExeSqlCommand(string sqlCommand, SqlParameter[] prams) { serlog(sqlCommand, prams); using SqlConnection sqlConnection = new SqlConnection(getstrConnection(null)); using SqlCommand sqlCommand2 = SqlDBA.CreateCommandSql(sqlConnection, sqlCommand, prams); int result = -1; try { sqlConnection.Open(); } catch { return -1; } try { result = sqlCommand2.ExecuteNonQuery(); } catch (Exception ex) { Setlog(sqlCommand, prams, ex); } sqlCommand2.Dispose(); sqlConnection.Close(); sqlConnection.Dispose(); return result; } public static int ExeSqlCommand(string sqlCommand, SqlParameter[] prams, string server) { serlog(sqlCommand, prams); using SqlConnection sqlConnection = new SqlConnection(getstrConnection(server)); using SqlCommand sqlCommand2 = SqlDBA.CreateCommandSql(sqlConnection, sqlCommand, prams); int result = -1; try { sqlConnection.Open(); } catch { return -1; } try { result = sqlCommand2.ExecuteNonQuery(); } catch (Exception ex) { Setlog(sqlCommand, prams, ex); } sqlCommand2.Dispose(); sqlConnection.Close(); sqlConnection.Dispose(); return result; } public static int ExeSqlCommand(string sqlCommand) { serlog(sqlCommand); using SqlConnection sqlConnection = new SqlConnection(getstrConnection(null)); using SqlCommand sqlCommand2 = new SqlCommand(sqlCommand, sqlConnection); int result = -1; try { sqlConnection.Open(); } catch { return -1; } try { result = sqlCommand2.ExecuteNonQuery(); } catch (Exception ex) { Setlog(sqlCommand, null, ex); } sqlCommand2.Dispose(); sqlConnection.Close(); sqlConnection.Dispose(); return result; } public static int ExeSqlCommand(string sqlCommand, string server) { serlog(sqlCommand); using SqlConnection sqlConnection = new SqlConnection(getstrConnection(server)); using SqlCommand sqlCommand2 = new SqlCommand(sqlCommand, sqlConnection); int result = -1; try { sqlConnection.Open(); } catch { return -1; } try { result = sqlCommand2.ExecuteNonQuery(); } catch (Exception ex) { Setlog(sqlCommand, null, ex); } sqlCommand2.Dispose(); sqlConnection.Close(); sqlConnection.Dispose(); return result; } public static int ExeSqlCommand(string sqlCommand, ref Exception exception, string db) { serlog(sqlCommand); using SqlConnection sqlConnection = new SqlConnection(getstrConnection(null)); using SqlCommand sqlCommand2 = new SqlCommand(sqlCommand, sqlConnection); try { sqlConnection.Open(); } catch (Exception ex) { Exception ex2 = (exception = ex); return -1; } int result = sqlCommand2.ExecuteNonQuery(); sqlCommand2.Dispose(); sqlConnection.Close(); sqlConnection.Dispose(); return result; } public static DataTable GetDBToDataTable(string sqlCommand, SqlParameter[] prams) { serlog(sqlCommand, prams); using SqlConnection sqlConnection = new SqlConnection(getstrConnection(null)); using SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(); SqlCommand sqlCommand5 = (sqlDataAdapter.SelectCommand = SqlDBA.CreateCommandSql(sqlConnection, sqlCommand, prams)); SqlCommand sqlCommand2 = sqlCommand5; SqlCommand sqlCommand3 = sqlCommand2; using (sqlCommand3) { try { sqlConnection.Open(); } catch (Exception ex) { Form1.WriteLine(100, "DBA数据层_错误" + ex.Message + " " + sqlCommand); return null; } DataTable dataTable = new DataTable(); try { sqlDataAdapter.Fill(dataTable); } catch (Exception ex2) { Setlog(sqlCommand, prams, ex2); } sqlDataAdapter.Dispose(); sqlConnection.Close(); sqlConnection.Dispose(); return dataTable; } } public static DataTable GetDBToDataTable(string sqlCommand, SqlParameter[] prams, string server) { serlog(sqlCommand, prams); using SqlConnection sqlConnection = new SqlConnection(getstrConnection(server)); using SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(); SqlCommand sqlCommand5 = (sqlDataAdapter.SelectCommand = SqlDBA.CreateCommandSql(sqlConnection, sqlCommand, prams)); SqlCommand sqlCommand2 = sqlCommand5; SqlCommand sqlCommand3 = sqlCommand2; using (sqlCommand3) { try { sqlConnection.Open(); } catch (Exception ex) { Form1.WriteLine(100, "DBA数据层_错误" + ex.Message + " " + sqlCommand); return null; } DataTable dataTable = new DataTable(); try { sqlDataAdapter.Fill(dataTable); } catch (Exception ex2) { Setlog(sqlCommand, prams, ex2); } sqlDataAdapter.Dispose(); sqlConnection.Close(); sqlConnection.Dispose(); return dataTable; } } public static DataTable GetDBToDataTable(string sqlCommand) { serlog(sqlCommand); using SqlConnection sqlConnection = new SqlConnection(getstrConnection(null)); using SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(); SqlCommand sqlCommand5 = (sqlDataAdapter.SelectCommand = new SqlCommand(sqlCommand, sqlConnection)); SqlCommand sqlCommand2 = sqlCommand5; SqlCommand sqlCommand3 = sqlCommand2; using (sqlCommand3) { try { sqlConnection.Open(); } catch (Exception ex) { Form1.WriteLine(100, "DBA数据层_错误" + ex.Message + " " + sqlCommand); return null; } DataTable dataTable = new DataTable(); try { sqlDataAdapter.Fill(dataTable); } catch (Exception ex2) { Setlog(sqlCommand, null, ex2); } sqlDataAdapter.Dispose(); sqlConnection.Close(); sqlConnection.Dispose(); return dataTable; } } public static DataTable GetDBToDataTable(string sqlCommand, string server) { serlog(sqlCommand); using SqlConnection sqlConnection = new SqlConnection(getstrConnection(server)); using SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(); SqlCommand sqlCommand5 = (sqlDataAdapter.SelectCommand = new SqlCommand(sqlCommand, sqlConnection)); SqlCommand sqlCommand2 = sqlCommand5; SqlCommand sqlCommand3 = sqlCommand2; using (sqlCommand3) { try { sqlConnection.Open(); } catch { return null; } DataTable dataTable = new DataTable(); try { sqlDataAdapter.Fill(dataTable); } catch (Exception ex) { Setlog(sqlCommand, null, ex); } sqlDataAdapter.Dispose(); sqlConnection.Close(); sqlConnection.Dispose(); return dataTable; } } public static DataRowCollection GetDBValue(string sqlCommand, string db) { return GetDBToDataTable(sqlCommand).Rows; } public static ArrayList GetDBValue_1(string sqlCommand, string db) { serlog(sqlCommand); using SqlConnection sqlConnection = new SqlConnection(getstrConnection(null)); using SqlCommand sqlCommand2 = new SqlCommand(sqlCommand, sqlConnection); try { sqlConnection.Open(); } catch { return null; } SqlDataReader sqlDataReader = sqlCommand2.ExecuteReader(); if (!sqlDataReader.HasRows) { sqlDataReader.Close(); sqlDataReader.Dispose(); sqlConnection.Close(); sqlConnection.Dispose(); return null; } ArrayList arrayList = new ArrayList(); if (sqlDataReader.Read()) { for (int i = 0; i < sqlDataReader.FieldCount; i++) { arrayList.Add(sqlDataReader[i]); } } sqlDataReader.Close(); sqlDataReader.Dispose(); sqlConnection.Close(); sqlConnection.Dispose(); sqlCommand2.Dispose(); return arrayList; } public static ArrayList GetDBValue_2(string sqlCommand, string db) { serlog(sqlCommand); using SqlConnection sqlConnection = new SqlConnection(getstrConnection(null)); using SqlCommand sqlCommand2 = new SqlCommand(sqlCommand, sqlConnection); try { sqlConnection.Open(); } catch { return null; } SqlDataReader sqlDataReader = sqlCommand2.ExecuteReader(); if (!sqlDataReader.HasRows) { sqlDataReader.Close(); sqlDataReader.Dispose(); sqlConnection.Close(); sqlConnection.Dispose(); return null; } ArrayList arrayList = new ArrayList(); while (sqlDataReader.Read()) { arrayList.Add(sqlDataReader[0]); } sqlDataReader.Close(); sqlDataReader.Dispose(); sqlConnection.Close(); sqlConnection.Dispose(); sqlCommand2.Dispose(); return arrayList; } public static object GetDBValue_3(string sqlCommand) { serlog(sqlCommand); object result = null; using SqlConnection sqlConnection = new SqlConnection(getstrConnection(null)); using SqlCommand sqlCommand2 = new SqlCommand(sqlCommand, sqlConnection); try { sqlConnection.Open(); } catch { return null; } try { result = sqlCommand2.ExecuteScalar(); } catch (Exception ex) { Form1.WriteLine(100, "DBA数据层_错误" + ex.Message + " " + sqlCommand); } sqlCommand2.Dispose(); sqlConnection.Close(); sqlConnection.Dispose(); return result; } public static object GetDBValue_3(string sqlCommand, SqlParameter[] prams) { serlog(sqlCommand, prams); object result = null; using SqlConnection sqlConnection = new SqlConnection(getstrConnection(null)); using SqlCommand sqlCommand2 = SqlDBA.CreateCommandSql(sqlConnection, sqlCommand, prams); try { sqlConnection.Open(); } catch { return null; } try { result = sqlCommand2.ExecuteScalar(); } catch (Exception ex) { Form1.WriteLine(100, "DBA数据层_错误" + ex.Message + " " + sqlCommand); } sqlCommand2.Dispose(); sqlConnection.Close(); sqlConnection.Dispose(); return result; } public static object GetDBValue_3(string sqlCommand, string db) { serlog(sqlCommand); object result = null; using SqlConnection sqlConnection = new SqlConnection(getstrConnection(db)); using SqlCommand sqlCommand2 = new SqlCommand(sqlCommand, sqlConnection); try { sqlConnection.Open(); } catch { return null; } try { result = sqlCommand2.ExecuteScalar(); } catch (Exception ex) { Form1.WriteLine(100, "DBA数据层_错误" + ex.Message + " " + sqlCommand); } sqlCommand2.Dispose(); sqlConnection.Close(); sqlConnection.Dispose(); return result; } } } 这是我的DBA类
最新发布
07-19
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值