Exporting a PostgreSQL query to a csv file using Python

杀马特。学长 韩版系。学妹 提交于 2019-11-26 21:51:44

问题


I need to export some rows from a table in a PostgreSQL database to a .csv file using a Python script:

#!/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()

...

But when I run the script I get this:

Syntax error at or near «\»
LINE 1: \copy (SELECT * FROM TABLE WHERE month=6) TO '...

Does anyone know what can be wrong or give me a tip about?


回答1:


The \copy is not an SQL command, it is a command specific for the Postgres terminal client psql and cannot be used in this context.

Use copy_expert(sql, file, size=8192) instead, e.g.:

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)



回答2:


\COPY is a psql command (client based) and therefore not a valid SQL command. Try the same simply using COPY (without the backslash\).

If you want the output file directly at the client, you might wanna use the STDOUT of COPY, otherwise the it will be created at the database server, which is a luxury not everyone has.



来源:https://stackoverflow.com/questions/49610908/exporting-a-postgresql-query-to-a-csv-file-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!