gpt4 book ai didi

postgresql - 在 PostgreSQL 中,如何使用 COPY 命令插入数据?

转载 作者:行者123 更新时间:2023-11-29 11:08:33 25 4
gpt4 key购买 nike

我在使用 PostgreSQL 数据库运行 1 个项目 NodeJs 时遇到问题。尝试使用 COPY 命令在 pgAdmin 中插入数据时出现错误。

COPY beer (name, tags, alcohol, brewery, id, brewery_id, image) FROM stdin;

Bons Voeux blonde 9.5 Brasserie Dupont 250 130 generic.png

这个数据在 gist :

这个错误:

ERROR: syntax error at or near "Bons"
SQL state: 42601
Character: 1967

I was create database like this and execute file .sql:

最佳答案

COPY tbl FROM <b>STDIN</b>;

pgAdmin 不支持。
您会得到一个简单的语法错误,因为 Postgres 将数据作为 SQL 代码获取。

四种可能的解决方案:

1。使用多行 INSERT 代替:

INSERT INTO beer(name, tags, alcohol, brewery, id, brewery_id, image)
VALUES
('Bons Voeux', 'blonde', 9.5, 'Brasserie Dupont', 250, 130, 'generic.png')
, ('Boerke Blond', 'blonde', 6.8, 'Brouwerij Angerik', 233, 287 'generic.png')
;

请注意值作为字符串或数字文字的不同 (SQL) 语法。

您可以使用 pg_dump using --inserts 生成数据.见:

2。使用 psql 作为特权系统用户

使用 psql 在命令行上调用您的脚本。作为系统用户 postgres:

psql -f beer.sql -U my_login_role -d db_name 

数据库(-d)和登录角色(-U 代表“用户”)如果默认值可以省略。语法示例:

确保默认的 text 格式有一个数据结束标记 (\.)。 (你有那个。)The manual:

End of data can be represented by a single line containing justbackslash-period (\.). An end-of-data marker is not necessary whenreading from a file, since the end of file serves perfectly well; itis needed only when copying data to or from client applications usingpre-3.0 client protocol.

3。 COPY 在具有特权数据库角色的数据库服务器上

将您的数据移动到服务器上的单独文件,例如“beer_data.csv”,然后使用COPY ... FROM 'filename' 在你的脚本中:

COPY beer (name, tags, alcohol, brewery, id, brewery_id, image)
FROM '/path/to/beer_data.csv';

不过,您需要 super 用户权限。 The manual:

[...] COPY naming a file or command is only allowed to database superusersor users who are granted one of the default rolespg_read_server_files, pg_write_server_files, orpg_execute_server_program, since it allows reading or writing any fileor running a program that the server has privileges to access.

(pg_read_server_filespg_write_server_filespg_execute_server_program 是 Postgres 11 中的新内容。)

4。 \copy 在任何客户端

使用 psql meta-command \copy 读取客户端 的本地文件.见:

关于postgresql - 在 PostgreSQL 中,如何使用 COPY 命令插入数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32271378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com