SQLCommand.ExecuteReader()不限制只读语句

Rya*_*ulx 3 c# sql sqldatareader readonly

显然,ExecuteReader用于只读,ExecuteNonQuery用于事务.但由于某些原因,即使我使用ExecuteReader,我仍然可以运行write(插入,更新,删除)命令(在textbox1中键入).我的代码有问题还是我误解了ExecuteReader的工作方式?

//MY CODE

string sqlStatement = textbox1.Text;

System.Data.SqlClient.SqlConnectionStringBuilder builder =
  new System.Data.SqlClient.SqlConnectionStringBuilder();
builder.DataSource = ActiveServer;
builder.IntegratedSecurity = true;

System.Data.SqlClient.SqlConnection Connection = new 
   System.Data.SqlClient.SqlConnection(builder.ConnectionString);
Connection.Open();

System.Data.SqlClient.SqlCommand command = new 
  System.Data.SqlClient.SqlCommand(sqlStatement, Connection);
System.Data.SqlClient.SqlDataReader reader = command.ExecuteReader();

dataGridView1.AutoGenerateColumns = true;

bindingSource1.DataSource = reader;
dataGridView1.DataSource = bindingSource1;

reader.Close();
Connection.Close();
Run Code Online (Sandbox Code Playgroud)

Ada*_*rth 6

ExecuteReader 只返回一个能够读取从SQL过程返回的行的阅读器 - 它不会阻止您在提供该结果集的过程中运行任意SQL.

执行插入/更新/删除然后立即返回结果集(因此从代码看起来像读取)可能有点奇怪(读取:代码气味),应该检查它是否可以分成不同的操作.


naw*_*fal 5

虽然两者都执行sql,ExecuteReader但是当ExecuteNonQuery 受影响的记录数量时,预计会返回记录.因此两者都不同.但内部有多么不同取决于供应商的具体实施.您可以ExecuteReader单独使用所有数据库操作,因为它只是工作(直到现在),但由于没有记录,它不是真正正确的方法.你可以更明确地表达自己的意图ExecuteNonQuery.

就性能而言,我认为根本不存在差异.我试着用SQLite,MySqlClient,SqlClient,SqlServerCeVistaDb看见没有明显的差异要么青睐.他们都应该以ExecuteReader某种方式在内部使用.

要点:

SqlClient中:

private int InternalExecuteNonQuery(DbAsyncResult result, string methodName, bool sendToPipe)
{
    if (!this._activeConnection.IsContextConnection)
    {
        if (this.BatchRPCMode || CommandType.Text != this.CommandType || this.GetParameterCount(this._parameters) != 0)
        {
            Bid.Trace("<sc.SqlCommand.ExecuteNonQuery|INFO> %d#, Command executed as RPC.\n", this.ObjectID);
            SqlDataReader sqlDataReader = this.RunExecuteReader(CommandBehavior.Default, RunBehavior.UntilDone, false, methodName, result);
            if (sqlDataReader == null)
            {
                goto IL_E5;
            }
            sqlDataReader.Close();
            goto IL_E5;
        }
    IL_B5:
        this.RunExecuteNonQueryTds(methodName, flag);
    }
    else
    {
        this.RunExecuteNonQuerySmi(sendToPipe);
    }
IL_E5:
    return this._rowsAffected;
}
Run Code Online (Sandbox Code Playgroud)

了MySqlClient:

public override int ExecuteNonQuery()
{
  int records = -1;

  #if !CF
  // give our interceptors a shot at it first
  if ( connection != null && 
       connection.commandInterceptor != null &&
       connection.commandInterceptor.ExecuteNonQuery(CommandText, ref records))
    return records;
  #endif

  // ok, none of our interceptors handled this so we default
  using (MySqlDataReader reader = ExecuteReader())
  {
    reader.Close();
    return reader.RecordsAffected;
  }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的那样MySqlClient直接调用ExecuteReader,SqlClient而且仅适用于某些条件.请注意insert,updates很少是瓶颈(通常是selects).

正如我所说,你不会在受到帮助的情况下获得受影响的行数ExecuteReader,因此ExecuteNonQuery最好使用它来执行查询.更直接的替换ExecuteReaderExecuteScalar返回第一行读取的第一列中的数据.

要点:

SqlClient中:

override public object ExecuteScalar()
{
    SqlConnection.ExecutePermission.Demand();

    // Reset _pendingCancel upon entry into any Execute - used to synchronize state
    // between entry into Execute* API and the thread obtaining the stateObject. 
    _pendingCancel = false;

    SqlStatistics statistics = null;
    IntPtr hscp;
    Bid.ScopeEnter(out hscp, "<sc.sqlcommand.executescalar|api> %d#", ObjectID);
    try
    {
        statistics = SqlStatistics.StartTimer(Statistics);
        SqlDataReader ds = RunExecuteReader(0, RunBehavior.ReturnImmediately, true, ADP.ExecuteScalar);

        object retResult = null;
        try
        {
            if (ds.Read())
            {
                if (ds.FieldCount > 0)
                {
                    retResult = ds.GetValue(0);
                }
            }
            return retResult;
        }
        finally
        {
            // clean off the wire 
            ds.Close();
        }
    }
    finally
    {
        SqlStatistics.StopTimer(statistics);
        Bid.ScopeLeave(ref hscp);
    }
}
Run Code Online (Sandbox Code Playgroud)

了MySqlClient:

public override object ExecuteScalar()
{
    lastInsertedId = -1;
    object val = null;

    #if !CF
    // give our interceptors a shot at it first
    if (connection != null &&
        connection.commandInterceptor.ExecuteScalar(CommandText, ref val))
        return val;
    #endif

    using (MySqlDataReader reader = ExecuteReader())
    {
        if (reader.Read())
            val = reader.GetValue(0);
    }

    return val;
}
Run Code Online (Sandbox Code Playgroud)

因此,使用它并没有任何伤害ExecuteReader,ExecuteScalar也没有任何性能差异.