简体   繁体   English

如何从delphi,参数在postgresql COPY命令中使用单引号插入文件名?

[英]how to insert filenames with single quotes in a postgresql COPY command from delphi, parameters?

I'm having some fun trying to include a filename in a Postgresql script in delphi, the desired string is 尝试在delphi中的Postgresql脚本中包含文件名时,我玩得很开心,所需的字符串是

  COPY myschema.mytable FROM 'c:\data\data.csv' CSV HEADER;

I know this SQL query is parsed ok by postgresql as I've tested it in pgadmin, the problem is how to generate it in Delphi. 我知道这个SQL查询可以通过PostgreSQL解析,因为我已经在pgadmin中对其进行了测试,问题是如何在Delphi中生成它。 Delphi uses single quotes for strings, so even using the QuotedStr method like Delphi对字符串使用单引号,因此即使使用QuotedStr方法,例如

TempSQL := 'COPY myschema.mytable FROM '+QuotedStr(myfilename)+ ' CSV HEADER';
ADOQuery1.SQL.Add (TempSQL);

the string is generated as 字符串生成为

COPY myschema.mytable FROM ''c:\data\data.csv'' CSV HEADER;

So I'm trying to use Parameters.ParamByName like 所以我想像这样使用Parameters.ParamByName

TempSQL := 'COPY myschema.mytable FROM :PFileName CSV HEADER';
ADOQuery1.SQL.Add (TempSQL);
FileNameParam := LQuery.Parameters.ParamByName('PFileName');
FileNameParam.DataType := ftstring;
FileNameParam.Value := 'c:\data\data.csv';
ADOQuery1.Open;

Gives the error: ERROR: syntax error at or near "$1"; 给出错误:ERROR:“ $ 1”或附近的语法错误; Error while executing the query. 执行查询时出错。 $1 is usually caused by paramnames being the same as column names, thats not the case here, I tried different paramnames. $ 1通常是由参数名与列名相同引起的,在这里不是这种情况,我尝试了不同的参数名。 I think the problem is that maybe Parambyname doesn't work for this type of argument, it's normally used like 我认为问题在于Parambyname不适用于这种类型的参数,通常使用

    SELECT * FROM myschema.mytable WHERE myfield = :myparameter

ie the colon comes after an = which isn't the case with the copy command. 也就是说,冒号位于=后面,而复制命令则不是这种情况。 Any suggestions welcome. 任何建议欢迎。 The delphi code basically scans a directory for (1000s of) suitable files and keeps a log of what is imported, maybe I have to interface with the db in a different way entirely. delphi代码基本上会在目录中扫描(数千个)合适的文件,并保留导入内容的日志,也许我必须以完全不同的方式与db接口。

This code works perfectly in a quick test app, and displays the properly quoted string in the call to ShowMessage , which means there's something other than what you've shown us here going on in your code. 该代码在快速测试应用程序中可以完美运行,并在对ShowMessage的调用中显示正确引用的字符串,这意味着您在代码中将看到的内容与您展示的内容有所不同。

procedure TForm4.FormCreate(Sender: TObject);
var
  TempStr: string;
  MyFileName: string;
begin
  MyFileName := 'somefile.txt';
  TempStr := 'COPY myschema.mytable FROM ' + QuotedStr(myfilename) + ' CSV HEADER';
  ShowMessage(TempStr);
end

The resulting dialog: 结果对话框:

该图在ShowMessage对话框中显示正确加引号的字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM