重用SqlCommand的? [英] Reusing SqlCommand?
问题描述
我真的不知道,如果这是可以或不可以。
I am not really sure if this is possible or not.
我目前工作的一个大学项目,我有一个使用存储过程的功能。我想知道是否有可能采取同样的的SqlCommand
实例和应用更新的参数相同的函数中调用到存储过程了。
I am currently working on a college project and I have a function that uses stored procedures. I would like to know if it is possible to take the same SqlCommand
instance and apply updated parameters to call into the stored procedure again within the same function.
可以说我有这样的事情在我的code:
Lets say i have something like this in my code:
myConStr = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
myConn = new SqlConnection(myConStr);
myCommand = new System.Data.SqlClient.SqlCommand("team5UserCurrentBooks3", myConn);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("@book_id", bookID);
myCommand.Parameters.AddWithValue("@user_id", userID);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
是否有可能更新 MyCommand
的参数,并再次调用存储过程?
Is it possible to update MyCommand
's parameters and call the stored procedure again?
推荐答案
是的。你要确保你是为了转储参数调用myCommand.Parameters.Clear每次调用之间,但没有什么重用对象阻止你。 (我不使用C#的时候,所以这可能在文本的错误或两个)
Yes. You'll want to make sure that you call myCommand.Parameters.Clear between each call in order to dump the parameters, but there's nothing stopping you from reusing the object. (I don't use C# often, so this may have an error or two in the text)
myConStr = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
myConn = new SqlConnection(myConStr);
myConn.Open();
myCommand = new System.Data.SqlClient.SqlCommand("team5UserCurrentBooks3", myConn);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("@book_id", bookID);
myCommand.Parameters.AddWithValue("@user_id", userID);
myCommand.ExecuteNonQuery();
myCommand.Parameters.Clear();
myCommand.CommandText= "NewStoredProcedureName";
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("@foo_id", fooId);
myCommand.Parameters.AddWithValue("@bar_id", barId);
mycommand.ExecuteNonQuery();
myCommand.Parameters.Clear();
myCommand.CommandText = " SELECT * FROM table1 WHERE ID = @TID;"
myCommand.CommandType = CommandType.Text;
myCommand.Parameters.AddWithValue("@tid", tId);
SqlReader rdr;
rdr = myCommand.ExecuteReader();
这篇关于重用SqlCommand的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!