小编Kan*_*Rev的帖子

SQLAlchemy - 如何从 ResultProxy 访问列名并写入 CSV 标头

我正在尝试使用 SQLAlchemy 建立与 PostgreSQL 数据库的连接,执行 SQL 查询并将文件的输出打印到 linux 中的文件。

from sqlalchemy import create_engine
import yaml
import csv

outfile = open('/path/filename.csv', 'wb')
outcsv = csv.writer(outfile, delimiter='\t')


with open('config.yml') as f:
    cfg = yaml.safe_load(f)
    username = cfg['credentials']['username']
    password = cfg['credentials']['password']
    host = cfg['credentials']['host'] 
    port = cfg['credentials']['port']
    dbname = cfg['credentials']['dbname']
    engine = create_engine('postgresql://{}:{}@{}:{}/{}'.format(username, password, host, port, dbname))
    result = engine.execute("""select * from db.tablename """)

    # dump column titles (optional)
    outcsv.writerow(x[0] for x in result.description)

    # dump rows
    outcsv.writerows(result.fetchall())
    outfile.close()
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误消息 - 回溯(最近一次调用最后一次):文件“”,第 12 …

python sqlalchemy

6
推荐指数
1
解决办法
7484
查看次数

标签 统计

python ×1

sqlalchemy ×1