如何在Python中使用psql“\ copy”?

时间:2015-03-02 12:30:12

标签: postgresql python-2.7 copy psycopg2 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()

这就是错误:

Error: syntax error at or near "\"
LINE 1: \copy stamm_data from '/home/jw/dev/test.csv' delimiter ';' ...
    ^

使用COPY时,我得到:

Error: could not open file "/home/jw/dev/test.csv" for reading: Permission denied

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

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

好的,我们转到.. copy_from的解决方案正常工作 - 我从csv文件中删除了标头,并使用copy_from导入该文件。

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

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

我的表格包含以下列:

ID, hotelcode, hotelname, stars

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