1

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"]);
4

2 回答 2

3

删除引号:

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

您的数据库将自动知道该字段是否为字符串,因此您无需将任何内容括在引号中。

于 2013-12-17T19:51:11.533 回答
2

您不需要参数化语句中的单引号。

更改此行:

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

对此:

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

您的sda.Parameters.AddWithValue调用将评估这些值是字符串,并正确传递它们,而无需在参数周围加上单引号。

于 2013-12-17T19:53:08.527 回答