使用Python将PostgreSQL查询导出到csv文件 [英] Exporting a PostgreSQL query to a csv file using Python

查看:693
本文介绍了使用Python将PostgreSQL查询导出到csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用Python脚本将PostgreSQL数据库中的表中的某些行导出到.csv文件:

I need to export some rows from a table in a PostgreSQL database to a .csv file using a Python script:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys, psycopg2

...

    conn = psycopg2.connect("dbname=dbname user=user password=password")
    cur = conn.cursor()

    sql = "\copy (SELECT * FROM table WHERE month=6) TO '/mnt/results/month/table.csv' WITH CSV DELIMITER ';';"
    cur.execute(sql)
    cur.close()

...

但是当我运行脚本时,我得到的是:

But when I run the script I get this:

Syntax error at or near «\»
LINE 1: \copy (SELECT * FROM TABLE WHERE month=6) TO '...

有人知道有什么问题或给我小费吗?

Does anyone know what can be wrong or give me a tip about?

推荐答案

\copy 不是SQL命令,它是特定于Postgres终端客户端 psql 的命令,因此不能在这种情况下使用。

The \copy is not an SQL command, it is a command specific for the Postgres terminal client psql and cannot be used in this context.

使用 copy_expert(sql ,文件,大小= 8192) ,例如:

Use copy_expert(sql, file, size=8192) instead, e.g.:

sql = "COPY (SELECT * FROM a_table WHERE month=6) TO STDOUT WITH CSV DELIMITER ';'"
with open("/mnt/results/month/table.csv", "w") as file:
    cur.copy_expert(sql, file)

这篇关于使用Python将PostgreSQL查询导出到csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆