I need to export some rows from a table in a PostgreSQL database to a .csv file using a Python script:
JavaScript
x
16
16
1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
3
4
import sys, psycopg2
5
6
7
8
conn = psycopg2.connect("dbname=dbname user=user password=password")
9
cur = conn.cursor()
10
11
sql = "copy (SELECT * FROM table WHERE month=6) TO '/mnt/results/month/table.csv' WITH CSV DELIMITER ';';"
12
cur.execute(sql)
13
cur.close()
14
15
16
But when I run the script I get this:
JavaScript
1
3
1
Syntax error at or near «»
2
LINE 1: copy (SELECT * FROM TABLE WHERE month=6) TO '...
3
Does anyone know what can be wrong or give me a tip about?
Advertisement
Answer
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.:
JavaScript
1
4
1
sql = "COPY (SELECT * FROM a_table WHERE month=6) TO STDOUT WITH CSV DELIMITER ';'"
2
with open("/mnt/results/month/table.csv", "w") as file:
3
cur.copy_expert(sql, file)
4
Read more about the function in the documentation.