虽然两者都执行 sql,但ExecuteReader
预计会在记录ExecuteNonQuery
数受到影响的情况下返回记录。两者因此不同。但在内部,它们有多大不同取决于供应商的具体实施。您可以ExecuteReader
单独使用所有数据库操作,因为它刚刚工作(直到现在),但由于它没有记录它并不是真正正确的方法。您可以更清楚地了解您的意图ExecuteNonQuery
。
就性能而言,我认为根本没有区别。我尝试了SQLite
, MySqlClient
, SqlClient
,SqlServerCe
并VistaDb
没有发现明显的差异。他们都应该在ExecuteReader
内部以一种或另一种方式使用。
要点:
客户端:
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;
}
和
MySql客户端:
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;
}
}
如您所见MySqlClient
,直接调用ExecuteReader
whileSqlClient
仅适用于某些条件。请注意,insert
s 和update
s 很少是瓶颈(通常是select
s)。
正如我所说,您不会在 的帮助下获得受影响的行数ExecuteReader
,因此请使用ExecuteNonQuery
更好的方法来执行查询。更直接的替换ExecuteReader
方法是ExecuteScalar
返回读取的第一行第一列中的数据。
要点:
客户端:
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);
}
}
和
MySql客户端:
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;
}
因此,使用ExecuteReader
forExecuteScalar
并没有任何性能差异。