gpt4 book ai didi

c# - 重用 SqlCommand?

转载 作者:IT王子 更新时间:2023-10-29 03:55:32 26 4
gpt4 key购买 nike

我不确定这是否可能。

我目前正在做一个大学项目,我有一个使用存储过程的函数。我想知道是否可以采用相同的 SqlCommand 实例并应用更新的参数以在同一函数内再次调用存储过程。

假设我的代码中有这样的东西:

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的参数并再次调用存储过程?

最佳答案

是的。您需要确保在每次调用之间调用 myCommand.Parameters.Clear 以转储参数,但没有什么可以阻止您重用该对象。 (我不常使用C#,所以文中可能会有一两处错误)

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();

关于c# - 重用 SqlCommand?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/670407/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com