[英]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#中写这个?
在字符串中的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.