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

标签 postgresql pgadmin bulk-load postgresql-copy

我在使用 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 just backslash-period (\.). An end-of-data marker is not necessary when reading from a file, since the end of file serves perfectly well; it is needed only when copying data to or from client applications using pre-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 superusers or users who are granted one of the default roles pg_read_server_files, pg_write_server_files, or pg_execute_server_program, since it allows reading or writing any file or 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/

相关文章:

postgresql - 使用 clojure.java.jdbc/db-do-prepared 检查 uuid 是否存在于 PostgreSQL 表中失败

sql - 如何检查给定模式中是否存在表

sql - 通过解除 JSON 数组的嵌套在 PostgreSQL 中进行批量更新

postgresql - 在 elixir 中使用 Ecto.Repo 时哪些函数被称为 'under the hood'

postgresql - 如何在 pgAdmin 中声明变量

sql - 如何将参数值添加到 pgadmin sql 查询?

postgresql - 无法使用 pgAdmin 读取 CSV 文件,

postgresql - 花时间从 csv 文件填充 POSTGRES 表

mysql - 将 MySQL 的 LOAD DATA INFILE 与 node.js 一起使用?