如何在Python中使用psql"\ copy"?

jwi*_*jwi 6 postgresql copy psycopg2 python-2.7 psql

我正在尝试将csv文件导入psql数据库.在阅读了之间的区别之后COPY,\copy我在执行脚本时遇到了这个错误.

这是我的代码切割:

try:

   csv_data = os.path.realpath('test.csv')

   con = psycopg2.connect(database = 'db01', user = 'postgres')
   cur = con.cursor()

   cur.execute("\copy stamm_data from '%s' DELIMITER ';' csv header" % csv_data)

   con.commit()
Run Code Online (Sandbox Code Playgroud)

这是错误:

Error: syntax error at or near "\"
LINE 1: \copy stamm_data from '/home/jw/dev/test.csv' delimiter ';' ...
    ^
Run Code Online (Sandbox Code Playgroud)

使用时COPY我得到:

Error: could not open file "/home/jw/dev/test.csv" for reading: Permission denied
Run Code Online (Sandbox Code Playgroud)

虽然psql用户'postgres'是超级用户,但运行该脚本的ubuntu用户对test.csv文件具有读取权限.

有任何想法吗?

jwi*_*jwi 1

好的,我们开始吧.. 解决方案copy_from工作正常 - 我从 csv 文件中删除标头并使用copy_from.

但现在我遇到了以下错误:

Error: null value in column "id" violates not-null constraint
DETAIL:  Failing row contains (null, foo01, ACE001, 3).
Run Code Online (Sandbox Code Playgroud)

我的表有以下列:

ID, hotelcode, hotelname, stars
Run Code Online (Sandbox Code Playgroud)

ID是我的PK,所以我不能删除NOT NULL修饰符。如何导入每行的 ID?或者我怎么说 Postgres 用值“DEFAULT”填充列 ID,以便数据库自行生成 id?

  • 如果有默认设置 int 应该可以工作。很高兴看到工作代码。 (4认同)