如何从远程数据库连接到本地计算机将Postgres结果集导出为CSV?

时间:2019-10-20 08:15:36

标签: python database postgresql csv copy

我正在使用 Psycopg2 将结果集数据从远程 PostgresQL DB 导出到本地计算机。

我有 SQL查询,可将结果集导出到CSV文件中。但是这些文件将在托管数据库的远程机器路径中创建。我正在使用 psycpog2 使用python连接到远程数据库。

据我了解,我们可以运行命令psql来按照How to insert CSV data into PostgreSQL database (remote database )中所述从终端导出CSV文件。

但是我如何使用Psycopg2 python做同样的事情。除了os.system('psql ... .. ..')以外,还没有其他方法可以使用 python 将CSV从远程数据库连接导出到我的本地。

1 个答案:

答案 0 :(得分:2)

使用游标类中的copy_tocopy_experthttp://initd.org/psycopg/docs/cursor.html

import sys
import psycopg2

db = psycopg2.connect("")

with db.cursor() as cursor:
    cursor.copy_expert(
        """copy (select * from pg_timezone_names) to stdout with csv header""",
        file=sys.stdout.buffer,
        size=256*1024
    )

要将数据发送到文件而不是stdout:

import psycopg2

db = psycopg2.connect("")

with open('myfile.csv', 'w') as f:
    with db.cursor() as cursor:
        cursor.copy_expert(
            """copy (select * from pg_timezone_names) to stdout with csv header""",
            file=f,
            size=256*1024
        )