从psycopg2查询中保存CSV文件的方法

2024-04-20 12:39:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试将python中执行的查询结果保存到一个local.csv中(使用psycopg2)。在

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

{a1}我甚至无法使用函数^ u进行复制:

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

这将引发错误“psycopg2.ProgrammingError:关系“records”不存在。

是否有更好的方法将查询结果存储在本地表中,并将其传入copy_to?谢谢你的建议!在


Tags: 文件csvthetofromiolocala1
2条回答

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

``` 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()
```

希望这有助于:

cursor.copy_to(COPY table TO file syntax)

所以在你的情况下:

^{pr2}$

相关问题 更多 >