[英]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.