Question

I am modifying a previous developers code and found that he was not using parameters in his update statements. I went to modify it with parameters to make it safer against injection and now it won't update at all. It did update with the old code. The code steps through just fine. It gives no errors but does not update the table. If the values are shown as

csharpa="Hello"
csharpb="Text"
csharpc="1"

during debugging. Checking the table for

select * from table where sqlb="Text" and sqlc="1" 

it still has the previous value in

sqla="Goodbye" 

not updated to Hello as I would expect.

Code before:

string q = "update table set sqla='" + 
    csharpa + "' where sqlb='" + csharpb + 
    "' and sqlc=" + (string)HttpContext.Current.Session["csharpc"];
SqlConnection conn = new SqlConnection(connstr);
SqlCommand sda = new SqlCommand(q, conn);
conn.Open();
sda.ExecuteNonQuery();
conn.Close();

Code After:

string q = "update table set sqla='@para' where sqlb='@parb' and sqlc=@parc";
SqlConnection conn = new SqlConnection(connstr);
SqlCommand sda = new SqlCommand(q, conn);
sda.Parameters.AddWithValue("@para", csharpa);
sda.Parameters.AddWithValue("@parb", csharpb);
sda.Parameters.AddWithValue("@parc", (string)HttpContext.Current.Session["csharpc"]);
Was it helpful?

Solution

Remove the quotes:

string q = "update table set sqla=@para where sqlb=@parb and sqlc=@parc";

Your DB will automatically know if the field is a string, so you don't need to enclose anything in quotes.

OTHER TIPS

You don't need the single quotes in your parameterized statement.

Change this line:

string q = "update table set sqla='@para' where sqlb='@parb' and sqlc=@parc";

to this:

string q = "update table set sqla=@para where sqlb=@parb and sqlc=@parc";

Your sda.Parameters.AddWithValue calls will evaluate that the values are strings, and pass them correctly without you having to put single quotes around the parameters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top