[英]Problems while importing a txt file into postgres using php
I am trying to import a txt/csv file into my postgres database from php using "\\copy" command.我正在尝试使用“\\copy”命令将 txt/csv 文件从 php 导入我的 postgres 数据库。 I cannot use COPY instead of \\copy as I need it to execute as a psql client.我不能使用 COPY 而不是 \\copy,因为我需要它作为 psql 客户端执行。 My code is:我的代码是:
$query = '\\'.'copy data1 FROM "data1.txt" WITH CSV HEADER DELIMITER AS "," QUOTE AS "^"';
$result = pg_query($conn,$query);
if (!$result) {
echo "cannot copy data\n";
} else {
echo "SUCCESS!";
}
When I run this php file, I get this error:当我运行这个 php 文件时,我收到这个错误:
PHP Warning: pg_query(): Query failed: ERROR: syntax error at or near "\"
LINE 1: \copy data1 FROM "data1.txt" WITH ...
^ in script.php on line 30
Actually, you cannot run \\copy
via pg_query()
.实际上,您不能通过pg_query()
运行\\copy
。 It is not an SQL command .它不是 SQL 命令。 It is a meta-command of the psql client .它是psql客户端的元命令。
There you can excute:在那里你可以执行:
\copy data1 FROM 'data1.txt' WITH CSV HEADER DELIMITER AS ',' QUOTE AS '^'
Or run the shell-command:或者运行 shell 命令:
psql mydb -c "\copy data1 FROM 'data1.txt'
WITH CSV HEADER DELIMITER AS ',' QUOTE AS '^'"
Note the quotes.注意引号。 Values need to be single-quoted in PostgreSQL : 'value'
.值需要在 PostgreSQL 中用单引号括起来: 'value'
。
Double-quotes are for identifiers - and are only actually needed for identifiers with upper case or illegal character or for reserved words: "My table"
.双引号用于标识符 - 只有大写或非法字符的标识符或保留字: "My table"
才真正需要。
I encountered the same problem, but instead of using the the raw psql
\\copy
command, decided to use the Ecto.Adapters.SQL.stream/2
function to read the contents of the file, and Repo.transaction/1
that executes the normal SQL COPY
command getting the data from STDIN
provided by the stream as described in this blog .我遇到了同样的问题,但没有使用原始的psql
\\copy
命令,决定使用Ecto.Adapters.SQL.stream/2
函数读取文件内容,而执行正常的Repo.transaction/1
SQL COPY
命令从流提供的STDIN
获取数据,如本博客所述。 I haven't tested the performance of this but i figured it would be a good addition to this answer.我还没有测试过它的性能,但我认为这将是对这个答案的一个很好的补充。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.