在字符串中加倍引号

时间:2014-10-02 10:03:00

标签: sql delphi insert double quotes

我在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

因此,当使用sql语句插入I''m时,它显然会起作用。但有时候,这段代码会出错,为什么会插入:

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

(引号的数量在这里是随机的)。而idk为什么,它确实最终退出添加引号但idk为什么有时它工作得很好,有时它的错误和添加太多的引号。

事实是,在大多数情况下,它会正确地加倍引号。但有时候为什么它变得疯狂并添加了太多的引号。

我在SQL中搜索加倍引号导致你必须将它们加倍才能转义它们并能够在你的表中正确插入它,如:

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

这会奏效。但我添加

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

它会创建一个错误,因为它会将我作为一个值,然后它将搜索分离I和m的昏迷。但我想你知道的。

无论如何,我的doublequoting功能不起作用。你能帮我发现它有什么问题吗?我的逻辑错了吗?谢谢。

1 个答案:

答案 0 :(得分:4)

在任何支持它的平台上,唯一的答案是使用参数化查询。虽然一开始看起来很烦人或令人沮丧,但它会好得多,并且值得您认为通过不使用它们而试图避免的任何挫败感。一旦你习惯它们,它们实际上更容易,更快。