2014-10-02 44 views
-2

我正在Delphi中使用Ado執行sql查詢(插入)。我的一些插入值有引號'。所以爲了插入他們的引號,你需要加倍他們。所以我做了一個函數:將字符串加倍引號

我的邏輯在這裏是使用一個while循環,因爲我會修改我的單詞的長度檢查,所以我有增量變量的控制權,我可以適當增量,以獲得無限循環。所以我檢查字符串的每個字符,如果它是一個報價,我添加另一個字符。

下面的代碼我使用:

//Search if there are ', if yes we need escape them 
    if Pos('''', aSourceData[i,j]) <> 0 then 
     begin 
     long := 0; 
     While long < Length(aSourceData[i,j]) do 
      begin 
      if aSourceData[i,j][long] = '''' then 
       begin 
       //here we found a ' copy string to it and double ' 
       aSourceData[i,j] := Copy(aSourceData[i,j], 0, long) + '''' 
            + Copy(aSourceData[i,j], long+1, Length(aSourceData[i,j])); 
       //we modified the string so the length of the word changed 
       //make sure to increment correctly or it's a endless loop 
       long := long +2; 

       end; 
      //Increment 
      long := long +1 ; 
      //if we don't check if the last character isn't a ' 
      //the loop will end before checking it and cause errors in sql string 
      if (long = Length(aSourceData[i,j])) AND (aSourceData[i,j][long] = '''') then 
       begin 
       //double the ' if found at the last position 
       aSourceData[i,j] := aSourceData[i,j] + ''''; 
       break; 
       end; 
      end; 
     end; 

這個事情的作品在大多數情況下。但有時完全相同的單詞我的函數添加太多的報價通常例如它:

I''m 

所以,當插入I''m與SQL語句會明顯工作。但有時,這種代碼中的bug IDK的原因,並將其插入:

I'''''''''''''m 

(報價數頃隨機這裏)。而idk爲什麼呢,它最終會退出添加引號,但idk爲什麼有時它很好用,有時它會出錯並增加太多引號。

問題是,在大多數情況下,它會正確加倍引號。但有時候idk爲什麼會變得瘋狂並且增加了太多引號。

我searchin用於加倍報價會導致SQL,你必須加倍他們逃離他們,並能夠正確地插入它在你的表所示:

Insert into mytable values('I''m quoted','I am not'); 

這會工作。但我添加

Insert into mytable values('I'mquotes','I am not'); 

它會創建一個錯誤導致它會採取我作爲一個值,然後它將搜索昏迷分離我和M。但我想你知道這一點。

無論如何,我的雙引號功能不起作用。你能幫我發現它有什麼問題嗎?我的邏輯錯了嗎?謝謝。

+0

使用內置的QuotedStr? – MartynA 2014-10-02 10:04:20

+0

你認真的已經有一個內置的方法嗎? x) – user28470 2014-10-02 10:05:27

+4

只需使用參數.... – bummi 2014-10-02 10:08:22

回答

4

在任何支持它的平臺上,唯一的答案就是使用參數化查詢。雖然起初它看起來很煩人或令人沮喪,但它好得多,並且值得你不想使用它們而試圖避免的任何挫折感。一旦習慣了它們,它們實際上變得更加簡單快捷。

+0

是的,我只是不知道有多少參數是,並且這是我的第一次嘗試。無論如何,我使它與雙引號 – user28470 2014-10-03 05:22:33