Reusing SqlCommand?

前端 未结 2 1029
情书的邮戳
情书的邮戳 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:53

    Yes! You can definitely do that. Within a function you can re-use the same connection as well (I don't recommend re-using a connection object for larger scopes, but it is possible).

    You could also do something like this:

    myConStr = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
    using (var cn = new SqlConnection(myConStr) )
    using (var cmd = new SqlCommand("team5UserCurrentBooks3", cn) ) 
    {
        cmd.CommandType = CommandType.StoredProcedure; 
        cmd.Parameters.Add("@user_id", SqlDbType.Int).Value = userID;
        cmd.Parameters.Add("@book_id", SqlDbType.Int);
        cn.Open();
    
        for(int i = 0; i<10; i++)
        {
            cmd.Parameters["@book_id"].Value = i;
            cmd.ExecuteNonQuery();
        }
    }
    

    This will run the query 10 times and use the same user_id each time it executes, but change the book_id. The using block is just like wrapping your connection in a try/catch to make sure it's closed.

提交回复
热议问题