如何从 psycopg2 中的查询保存 CSV 文件

sc2*_*c28 4 python csv postgresql psycopg2

我试图将 python 中对 PostgreSQL 数据库执行的查询结果保存在本地 .csv 中(使用 psycopg2)。

我可以在控制台中打印查询结果,但无法将其导出到 csv 文件。

我尝试过使用 copy_to 函数,但即使有文档我也无法弄清楚:

    # Retrieve the records from the database with query
    cursor.execute("SELECT col1 FROM myDB.myTable WHERE col1 > 2")
    records = cursor.fetchall()

    # Save to csv with copy_to
    io = open('copy_to.csv', 'w')
    cursor.copy_to(io, 'records', ',')
    print("Copied records from query into file object using sep = ,")
    io.close()
Run Code Online (Sandbox Code Playgroud)

这会引发错误“psycopg2.ProgrammingError:关系“记录”不存在”。

是否有更好的方法将查询结果存储在可以在copy_to中传递的本地表中?感谢您的任何提示!

Sco*_*key 5

我做了更多研究,这是另一个可能更有效的解决方案:

``` python
import psycopg2

#note the lack of trailing semi-colon in the query string, as per the Postgres documentation
s = "'SELECT col1 FROM myDB.myTable WHERE col1 > 2'"

conn = psycopg2.connect...
db_cursor = conn.cursor()

SQL_for_file_output = "COPY ({0}) TO STDOUT WITH CSV HEADER".format(s)

WITH Open(filepath/name, 'w') as f_output:
    cur.copy_expert(SQL_for_file_output, f_output)

conn.close()
```
Run Code Online (Sandbox Code Playgroud)