我需要使用Python脚本将PostgreSQL数据库中的表中的某些行导出到.csv文件:
#!/usr/bin/python # -*- coding: utf-8 -*- import sys, psycopg2 ... conn = psycopg2.connect("dbname=dbname user=user password=password") cur = conn.cursor() sql = "\copy (SELECT * FROM table WHERE month=6) TO '/mnt/results/month/table.csv' WITH CSV DELIMITER ';';" cur.execute(sql) cur.close() ...
但是当我运行脚本时,我得到了:
Syntax error at or near «\» LINE 1: \copy (SELECT * FROM TABLE WHERE month=6) TO '...
有谁知道可能出什么问题或给我小费吗?
该\copy命令不是SQL命令,它是Postgres终端客户端 psql 专用的命令,不能在此上下文中使用。
\copy
使用copy_expert(sql, file, size=8192)代替,例如:
copy_expert(sql, file, size=8192)
sql = "COPY (SELECT * FROM a_table WHERE month=6) TO STDOUT WITH CSV DELIMITER ';'" with open("/mnt/results/month/table.csv", "w") as file: cur.copy_expert(sql, file)