在基于C#中的存储过程执行查询后,如何为CommandText重用SqlCommand对象?
我有一个示例代码
aCommand.CommandType = CommandType.StoredProcedure; aCommand.Parameters.AddWithValue("@book_id", bookID); aCommand.Parameters.AddWithValue("@user_id", userID);
之后我想使用CommandText
执行一个简单的查询:
aCommand.CommandText = "SELECT * FROM aTABLE"; aCommand.ExecuteNonQuery();
但是错误发生了:
例外:找不到存储过程’SELECT * FROM aTABLE’
在这种情况下,我必须创建一个新的SqlCommand
对象实例?
这是一种使用相同的SqlCommand
对象来避免创建一个的方法吗?
它应该是
aCommand.CommandType = CommandType.Text
实际上, CommandType
的默认值是CommandType.Text
问题是您已经重用了一个SqlCommand
, CommandType
是StoredProcedure
但您想要使用CommandType.Text
执行正常的SQL查询。
“在这种情况下,我必须创建一个新的SqlCommand对象实例?”
我建议这样做是为了避免这种混淆。 创建SqlCommand
并不是那么昂贵,您需要重用它。 实际上构造函数只不过是设置属性。
来自ILSpy
:
// System.Data.SqlClient.SqlCommand // this() does only call _SuppressFinalize public SqlCommand(string cmdText, SqlConnection connection) : this() { this.CommandText = cmdText; this.Connection = connection; }
aCommand.CommandType = CommandType.StoredProcedure; aCommand.Parameters.AddWithValue("@book_id", bookID); aCommand.Parameters.AddWithValue("@user_id", userID);
-
指定您调用的存储过程名称
aCommand.CommandText=yourstoredprocedurename; aCommand.ExecuteNonQuery();
-
然后调用你的select和sqlreader来获得结果
bCommand.CommandType = CommandType.Text bCommand.CommandText = "SELECT * FROM aTABLE"; SqlDataReader rdr = bCommand.ExecuteReader();
您必须构造新的Command
对象以擦除先前设置的参数和值。
aCommand=new SqlCommand(); aCommand.Connection=cn; aCommand.CommandText = "SELECT * FROM aTABLE"; SqlDataReader reader=aCommand.ExecuteReader();
调用ExecuteReader()
方法而不是ExecuteNonQuery
来获取数据库结果。