簡體   English   中英

C#中的MSSQL查詢,從字符串獲取WHERE子句的一部分

[英]MSSQL query in C#, Geting part of WHERE clause from a string

我正在使用以下代碼:

string str = "ID = 15";

using (SqlCommand cmd = new SqlCommand("SELECT * " + 
                                       "FROM Cutomer" + 
                                       " Where (Status='Umbruch') and '"+str+"' " , con))

我收到此錯誤:

near 'ID = 15' is a non boolean expression specified in a context where a condition is expected. 

我知道我可以像這樣使用上面的代碼:

int id = 15; 

using (SqlCommand cmd = new SqlCommand("SELECT * " + 
                                       "FROM Cutomer" + 
                                       " Where (Status='Umbruch') and (ID='"+str+"')" , con))

這樣工作正常,但我想按上面第一個代碼中所述使用它。 由於ID的數量不是固定的,因此可以為2,3或更大。 為了簡單起見,我將代碼放在這里。

第一個版本應該是(從第二個“有效”查詢中,您需要在15附近加上簡單的引號,而不是整個表達式周圍)。

str = "ID = '15'";

using (SqlCommand cmd = new SqlCommand("SELECT * " + 
                                       "FROM Cutomer" + 
                                       " Where (Status='Umbruch') and "+str , con))

順便說一句,您應該使用參數,而不是直接字符串。

如果您需要一個IN子句,則可以查看該問題

一個簡單的錯誤,不要在字符串前后加上單引號

using (SqlCommand cmd = new SqlCommand("SELECT * FROM Cutomer " + 
                                       "WHERE (Status='Umbruch') AND " + str , con))

當然,這假定您的ID字段是數字字段而不是文本字段。
在后一種情況下,您應該將單引號放在15個常數周圍

string str = "ID = '15'";

附帶說明一下,請記住,字符串連接確實很危險,因為可以通過簡單的Sql Injection攻擊來利用您的代碼。 在這種非常特殊的情況下,不可能進行注射。

如果您從用戶輸入中收到要搜索的ID,請不要使用字符串串聯來構建sql命令。 而是使用參數化查詢

 using (SqlCommand cmd = new SqlCommand("SELECT * FROM Cutomer " + 
                               " Where (Status='Umbruch') and ID=@custID" , con))
 {
      cmd.Parameters.AddWithValue("@custID", 15);
      ......
 }

您在這里將其設為文字:

using (SqlCommand cmd = new SqlCommand("SELECT * " + 
                                       "FROM Cutomer" + 
                                       " Where (Status='Umbruch') and '"+str+"' " , con))

它應該是:

using (SqlCommand cmd = new SqlCommand("SELECT * " + 
                                       "FROM Cutomer" + 
                                       " Where (Status='Umbruch') and "+str, con))

請注意,刪除了'的細微差別。

此外,請閱讀我的博客文章 ,了解為什么您願意接受SQL注入以及為什么需要利用參數化SQL而不是原始SQL。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM