我正在使用 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从远程数据库连接导出到我的本地。
答案 0 :(得分:2)
使用游标类中的copy_to
或copy_expert
。 http://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
)