gpt4 book ai didi

c# - 带单引号的 SQL 查询

转载 作者:搜寻专家 更新时间:2023-10-30 21:52:33 25 4
gpt4 key购买 nike

执行此查询时出现错误,因为列文本也可能包含带单引号的文本。我如何在没有任何错误的情况下使用此查询我的代码是

public bool updateCMStable(int id, string columnName, string columnText)
{
try
{
string sql = "UPDATE CMStable SET " + columnName +
"='" + columnText + "' WHERE cmsID=" + id;
int i = SqlHelper.ExecuteNonQuery(Connection.ConnectionString,
CommandType.Text,
sql);
if (i > 0)
{
return true;
}
else
{
return false;
}
}
catch (Exception ee)
{
throw ee;
}
}

最佳答案

您应该使用 parameterized queries 而不是在字符串中构建 SQL - 除了单引号问题外,您当前的代码还容易受到 SQL Injection 的攻击。 .

存在一个限制,因为您尝试使用无法参数化的动态列名,但您仍然可以以更安全的方式使用动态 SQL。

我建议阅读 The Curse and Blessings of Dynamic SQL Erland Sommarskog 对该主题进行了综合处理。

关于c# - 带单引号的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11374271/

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