gpt4 book ai didi

c# - 带有 ORDER BY 的 SQL 查询语法不起作用

转载 作者:太空狗 更新时间:2023-10-29 23:57:18 24 4
gpt4 key购买 nike

我是 C# 的新手,但我非常了解 SQL。我有一个在 SQL 编辑器中运行良好的查询,但我无法将它集成到我的代码中。它抛出错误的 SQL 语法异常。可以正常工作的原始 SQL 查询是:

select distinct description from Table_A where id = '001' order by description;

C# 字符串如下:

_cmd.CommandText = "select distinct description from Table_A where Plant_ID =" + _selectedPlantID + "order by description";

当我删除 + "order by description 部分时,上面的查询在 C# 程序中有效。这里 _selectedPlantID 是唯一在程序中获取值的变量。我是很确定应该有一些引号问题,但对我来说一切看起来都很好,所以想知道是否有任何其他特定的方法可以用 C# 编写这个?

最佳答案

这是将 1 替换为 _selectedPlantID 后您的 SQL 在 C# 中的样子:

select distinct description from Table_A where id =1order by description

你看到问题了吗?

但是,请使用 parameterized queries 而不是添加空格来“修复”问题反而。您刚刚遇到的这个问题只是“拼接字符串和参数”问题的一个;然而,最危险的是 SQL injection .

关于c# - 带有 ORDER BY 的 SQL 查询语法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22538704/

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