簡體   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