Reusing SqlCommand?

前端 未结 2 1023
情书的邮戳
情书的邮戳 2020-12-03 04:25

I am not really sure if this is possible or not.

I am currently working on a college project and I have a function that uses stored procedures. I would like to know

2条回答
  •  执笔经年
    2020-12-03 04:50

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

提交回复
热议问题