Delphi Tstringlist,获取字符串作为带引号、逗号分隔的字符串?

use*_*752 3 csv delphi tstringlist

我有一个 Tstringlist,其中包含数据库表中使用的键列表。我想要一种简单的方法来生成一个包含所有键的字符串,每个键用逗号分隔并用单引号引起来。这样它就可以在 SQL 'IN' 语句中使用,例如WHERE FieldX IN ('One','Two','Three')

我尝试过使用 quotechar 但在读取逗号文本时它会被忽略。例如下面的代码

procedure junk;
var
  SL : Tstringlist;
  s : string;
begin
 SL := Tstringlist.Create;
 SL.Delimiter :=','; //comma delimiter
 SL.QuoteChar := ''''; //single quote around strings
 SL.Add('One');
 SL.Add('Two');
 SL.Add('Three');
 try
   s :=  SL.commatext;
   showmessage(s);
 finally
   SL.Free;
 end; //finally
end; //junk
Run Code Online (Sandbox Code Playgroud)

显示消息一、二、三 - 不带任何引号。

我知道我可以从长远来看,就像

procedure junk;
var
  SL : Tstringlist;
  s : string;
  i : integer;
begin
 SL := Tstringlist.Create;
 SL.Delimiter :=','; //comma delimiter
 SL.Add('One');
 SL.Add('Two');
 SL.Add('Three');
 try
 s := '';
 for I := 0 to SL.Count - 1 do
    begin
    s := s +  ',' + '''' + SL[i] + '''';
    end;
 delete(s,1,1);
 showmessage(s);
 finally
   SL.Free;
 end;//finally
end;
Run Code Online (Sandbox Code Playgroud)

但是有没有更简单的方法使用 Tstringlist 本身的属性?

Hea*_*are 5

如果您使用的是 D2006 或更高版本,则可以使用 CLASS HELPER:

USES Classes,StrUtils;

TYPE
  TStringListHelper = CLASS HELPER FOR TStrings
                        FUNCTION ToSQL : STRING;
                      END;

FUNCTION TStringListHelper.ToSQL : STRING;
  VAR
    S : STRING;

  FUNCTION QuotedStr(CONST S : STRING) : STRING;
    BEGIN
      Result:=''''+ReplaceStr(S,'''','''''')+''''
    END;

  BEGIN
    Result:='';
    FOR S IN Self DO BEGIN
      IF Result='' THEN Result:='(' ELSE Result:=Result+',';
      Result:=Result+QuotedStr(S)
    END;
    IF Result<>'' THEN Result:=Result+')'
  END;
Run Code Online (Sandbox Code Playgroud)

这段代码:

SL:=TStringList.Create;
SL.Add('One');
SL.Add('Two');
SL.Add('Number Three');
SL.Add('It''s number 4');
WRITELN('SELECT * FROM TABLE WHERE FIELD IN '+SL.ToSQL);
Run Code Online (Sandbox Code Playgroud)

然后将输出:

SELECT * FROM TABLE WHERE FIELD IN ('One','Two','Number Three','It''s number 4')
Run Code Online (Sandbox Code Playgroud)