Parameters.AddWithValue("@parameter", value) method

Keywords: Stored Procedure

Links to the original text: https://www.cnblogs.com/kdp0213/p/8532838.html

Differences between the cmd.Parameters.Add method and the VS Parameters.AddWithValue("@parameter", value) method

In the past, when using command method to add parameters to stored procedures, we always used cmd.Parameters.Add method to set parameters and parameter types, and then used Parameters[0].Value to assign parameters. A previous action code example:

string strConn = "Data Source=.;Initial Catalog=HISDB;Integrated Security=True";
using( SqlConnection conn = new SqlConnection(strConn))
{
    conn.Open();
    SqlCommand cmd = new SqlCommand("AuditMessageInsert", conn);
    //Setting the command type to a stored procedure will fail if it is not set
    cmd.CommandType = CommandType.StoredProcedure;
    //Setting parameter names and types
    cmd.Parameters.Add("@Target", SqlDbType.NChar);
    cmd.Parameters.Add("@Description", SqlDbType.NChar);
    cmd.Parameters.Add("@Actor", SqlDbType.NChar);
    cmd.Parameters.Add("@Time", SqlDbType.DateTime);
    cmd.Parameters.Add("@Computer", SqlDbType.NChar);
    //Assignment of parameters
    cmd.Parameters[0].Value = "ATarget";
    cmd.Parameters[1].Value = "Description";
    cmd.Parameters[2].Value = "Actor";
    cmd.Parameters[3].Value = DateTime.Now;
    cmd.Parameters[4].Value = "PC-Computer";
    cmd.ExecuteNonQuery();
}

If you use the Parameters.AddWithValue method, you can add the parameter name and its value directly without setting the type of the parameter. The sample code is as follows:

string strConn = "Data Source=.;Initial Catalog=HISDB;Integrated Security=True";
using( SqlConnection conn = new SqlConnection(strConn))
{
    conn.Open();
    SqlCommand cmd = new SqlCommand("AuditMessageInsert", conn);
   
    cmd.CommandType = CommandType.StoredProcedure;
   
 
    //Increase parameters: name and type, regardless of the order of the parameters in the table
    cmd.Parameters.AddWithValue("@Actor", "Actor");
    cmd.Parameters.AddWithValue("@Target", "Target");
    cmd.Parameters.AddWithValue("@Description", "Description");

    cmd.Parameters.AddWithValue("@Computer", "Computer");
    cmd.Parameters.AddWithValue("@Time", DateTime.Now);


    cmd.ExecuteNonQuery();
}

Posted by rmt123 on Wed, 09 Oct 2019 12:47:59 -0700