繁体   English   中英

ORDER BY的SQL查询语法不起作用

[英]SQL query syntax with ORDER BY not working

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

从Table_A中选择不同的描述,其中id ='001'按顺序排序;

C#字符串就像:

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

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

在将# 1替换为_selectedPlantID之后,这就是SQL在C#中的_selectedPlantID

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

你看到了问题?

但是,请使用参数化查询 ,而不是添加空间来“修复”问题。 你刚才遇到过这个问题仅仅是“连接字符串和参数”的烦恼之一 ; 然而,最危险的是SQL注入

在字符串中的ORDER BY子句之前需要一个空格,如下所示:

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

你错过了"'order by之间的空格,这样可行:

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

但由于它对SQL Injection( 此处为综合示例)开放,请考虑使用参数化查询

_cmd.CommandText = "select distinct description from Table_A where Plant_ID = ? order by description";
command.Parameters.AddWithValue("@plant", _selectedPlantID );

使用string.Format通常也是连接字符串的好方法,特别是如果要组合很多字符串:

_cmd.CommandText = string.Format("select distinct description from Table_A where Plant_ID ='{0}' order by description", _selectedPlantID);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM