Click here to Skip to main content
15,896,111 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to insert values to table using Insert into statement.For that I used it like this.
C#
SqlCommand sqlCommand = new SqlCommand("Insert into item(itemcode,name) values (@itemcode,@itemName)");

Then I added parameters like this.
SqlParameter[] parameterList = new SqlParameter[2];

SqlParameter paraItemcode = new SqlParameter("@ItemCode", SqlDbType.Char);
paraItemcode.Value = anyValue;
parameterList[0] = paraItemcode;

SqlParameter paraName = new SqlParameter("@itemName", SqlDbType.VarChar);
paraName.Value = anyName;
parameterList[1] = paraName;

sqlCommand.Parameters.AddRange(parameterList);

Rather adding parameters like this, I can add parameters like this also
sqlCommand.Parameters.Add("@itemCode",SqlDbType.Char).Value=anyValue;
sqlCommand.Parameters.Add("@itemName",SqlDbType.VarChar).Value=anyName;

From those two, which approach is the best practice to use?
Posted
Updated 26-Apr-11 0:38am
v2

Both approaches produce the same result, so from that point of view none of the two is better than the other. The second one eliminates having to fumble around with an array and is far less verbose. I think it makes the clearer and easier to understand and that's why I would go with that one.

Edit: The question might not be how to attach parameters to a command. It's far more important to isolate data access in a separate layer. There (and only there) should commands and parameters be constructed and used.
 
Share this answer
 
v2
I use a method based on the second one! And I find this works best for me.

Because I wanted to create a method that can have many parameters I created it using a Generic List, so I can pass Parameter Name, Value and data type.
 
Share this answer
 
All the approaches are same and will give you the same result. Using second approach you can save some line of code.
You can do the same thing with the below approach also

SqlParameter[] param = new SqlParameter[]
{
     new SqlParameter("@itemName", 10),
     new SqlParameter("@ItemCode", "Namw")
};

sqlCommand.Parameters.AddRange(parameterList);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900