2017-02-20 61 views
2

幾個,我的計劃是處理創建在讀取日誌表中的記錄中的記錄:VB.Net:逃避查詢字符串單打引號使用一個變量,單引號

儀器:不正確的語法's'附近。在字符串'))'之後未使用引號。

該代碼使用內聯查詢,該查詢將字符串變量的值連接到SELECT和SubQueries中的WHERE子句。

代碼:

SQL = "SELECT instrument_id, description, sub_category_of, meta_instrument" _ 
& " FROM instruments " _ 
& " WHERE (instrument_id IN " _ 
& " (SELECT instrument_id " _ 
    & "FROM instruments " _ 
    & "WHERE (description = '" & strn & "'))) " _ 
     & "OR (instrument_id IN " _ 
     & " (SELECT sub_category_of " _ 
     & "  FROM instruments AS instruments_1 " _ 
     & "  WHERE (description = '" & strn & "'))) " _ 
     & "OR (instrument_id IN " _ 
     & " (SELECT meta_instrument " _ 
     & "  FROM instruments AS instruments_1 " _ 
     & "  WHERE (description = '" & strn & "')))" 

是被針對SQL Server執行的實際查詢:

SELECT instrument_id, description, sub_category_of, meta_instrument _ 
FROM instrument_ref 
    WHERE (instrument_id IN 
(SELECT instrument_id 
    FROM instruments 
    WHERE (description = 'Women's Choir'))) 
    OR (instrument_id IN 
     (SELECT sub_category_of 
      FROM instruments AS instruments_1 
      WHERE (description = 'Women's Choir'))) 
    OR (instrument_id IN 
     (SELECT meta_instrument 
      FROM instruments AS instruments_1 
      WHERE (description = 'Women's Choir'))) 

我想怎麼單引號可以讓這個錯誤可以被處理,以尋求幫助被糾正。我是否在'strn'變量中轉義它,還是在內聯查詢中執行?

非常感謝。

+0

用''替換'' – artm

+5

使用參數來提供您的信息以避免這些問題。 – LarsTech

+2

......這些問題和*許多*其他 – Plutonix

回答

2

至於建議,使用參數:

SQL = "SELECT instrument_id, description, sub_category_of, meta_instrument" _ 
& " FROM instruments " _ 
& " WHERE (instrument_id IN " _ 
& " (SELECT instrument_id " _ 
    & "FROM instruments " _ 
    & "WHERE (description = @description))) " _ 
     & "OR (instrument_id IN " _ 
     & " (SELECT sub_category_of " _ 
     & "  FROM instruments AS instruments_1 " ... etc 

然後,當你構建SqlCommand對象與此SQL,使用命令對象的「.Parameters.AddWithValue()」方法來添加一個名爲「@description參數「和適當的價值。

順便說一句,通過輸入「drop table instruments」的描述來防止某人造成嚴重破壞。

+4

參數很好,但AddWithValue不是。請參閱http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/ –

+0

謝謝丹......說得很好。 –