gene
gene

Reputation: 2108

Adding parameters to stored procedure in C# with AddWithValue method

I'm fixing SQL Injections in the code. One of the method executes stored procedure and append parameters violating SQL Injections rules:

sqlCmd.CommandText = "updateSalesReps @repNumber='" + RepNumber + "', 
@ISONumber='" + ISONumber + "', @type='" + strUpdtType + "'";

Now, I'm adding parameters:

sqlCmd.Parameters.AddWithValue("@rNumber", RepNumber);
sqlCmd.Parameters.AddWithValue("@isoNumber", ISONumber);
sqlCmd.Parameters.AddWithValue("@updateType",strUpdtType);

This is my final query:

 sqlCmd.CommandText = "updateSalesReps @repNumber=@repNumber, 
 @ISONumber=@isoNumber, @type=@updateType";

My question is if it is OK to have ...@repNumber=@repNumber... in my stored procedure or it will create naming ambiguity?

Upvotes: 0

Views: 2489

Answers (1)

Elliot Rodriguez
Elliot Rodriguez

Reputation: 618

If you specify the commandType and commandText properties on the command object you dont need to do that. Assuming you're using SQL Server stored procs, try:

   SqlCommand sqlCmd = new SqlCommand();
   sqlCmd.CommandTimeout = 15;
   sqlCmd.CommandType = CommandType.StoredProcedure;
   sqlCmd.CommandText = "updateSalesReps"

Then add to your parameters collection using AddWithValue.

Reference: CommandType in MSDN

When you set the CommandType property to StoredProcedure, you should set the CommandText property to the name of the stored procedure. The command executes this stored procedure when you call one of the Execute methods.

Upvotes: 2

Related Questions