gpt4 book ai didi

c# - 带参数的 SQLCommand 不再更新我的表

转载 作者:太空宇宙 更新时间:2023-11-03 20:09:57 25 4
gpt4 key购买 nike

我正在修改以前的开发人员代码,发现他没有在他的更新语句中使用参数。我去用参数修改它以使其更安全地防止注入(inject),现在它根本不会更新。它确实使用旧代码进行了更新。代码逐步完成。它没有给出错误但不更新表。如果值显示为

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

调试期间。检查表

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

它仍然具有以前的值

sqla="Goodbye" 

没有像我预期的那样更新为 Hello。

之前的代码:

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();

之后的代码:

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

最佳答案

删除引号:

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

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

关于c# - 带参数的 SQLCommand 不再更新我的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20643347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com