views:

466

answers:

2
+4  A: 

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.CommandText = " SELECT * FROM table1 WHERE ID = @TID;"
myCommand.Parameters.Clear();
myCommand.CommandText= "NewStoredProcedureName";
myCommand.CommandType = CommandType.Text;
myCommand.Parameters.AddWithValue("@tid", tId);
SqlReader rdr;
rdr = myCommand.ExecuteReader();
Stephen Wrighton
+4  A: 

Yes! You can definitely do that. You can re-use the same connection as well.

You could also do something like this:

myConStr = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
using (var cn = new SqlConnection(myConStr) )
using (var cmd = new SqlCommand("team5UserCurrentBooks3", myConn) ) 
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@book_id", SqlDbType.Int).Value = bookID;
    cmd.Parameters.Add("@user_id", SqlDbType.Int).Value = userID;

    cn.Open();
    cmd.ExecuteNonQuery();
}

This is just like wrapping your connection in a try/catch to make sure it's closed.

Joel Coehoorn
unfortunately Parameters.Add is obsolete now.But i Like you idea about using
Dmitris
@Dmitris, Only the Add(string, object) overload is obsolete. All the other overloads of Add are fine to use - see http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.add.aspx for more info.
LukeH