簡體   English   中英

如何從psycopg2中的查詢保存CSV文件

[英]How to save CSV file from query in psycopg2

我正在嘗試將在 python 中對 PostgreSQL 數據庫(使用 psycopg2)執行的查詢結果保存在本地 .csv 中。

我可以在控制台中打印查詢結果,但無法將其導出到 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()

這會引發錯誤“psycopg2.ProgrammingError:關系“記錄”不存在”。

有沒有更好的方法將查詢結果存儲在可以在copy_to 中傳遞的本地表中? 感謝您提供任何提示!

希望這有助於:

cursor.copy_to(COPY table TO file syntax)

所以在你的情況下:

cursor.copy_to(COPY records TO io)

我做了更多的研究,這里是另一種可能更有效的解決方案:

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

這對我有用:

csv_file = open('myFile.csv', 'w')

cursor = finbot.conn.cursor()
cursor.copy_to(csv_file, 'table_name', sep=",")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM