从 sqlalchemy 转储 csv [英] dump csv from sqlalchemy
问题描述
出于某种原因,我想以 csv 文件的形式从数据库 (sqlite3) 转储一个表.我正在使用带有 elixir(基于 sqlalchemy)的 python 脚本来修改数据库.我想知道是否有任何方法可以将我使用的表格转储到 csv.
For some reason, I want to dump a table from a database (sqlite3) in the form of a csv file. I'm using a python script with elixir (based on sqlalchemy) to modify the database. I was wondering if there is any way to dump the table I use to csv.
我见过 sqlalchemy serializer 但它似乎没有成为我想要的.我做错了吗?我应该在关闭 sqlalchemy 会话后调用 sqlite3 python 模块来转储到文件吗?还是我应该使用自制的东西?
I've seen sqlalchemy serializer but it doesn't seem to be what I want. Am I doing it wrong? Should I call the sqlite3 python module after closing my sqlalchemy session to dump to a file instead? Or should I use something homemade?
推荐答案
有很多方法可以实现这一点,包括一个简单的os.system()
调用sqlite3
> 实用程序,如果你安装了它,但这里大致是我用 Python 做的:
There are numerous ways to achieve this, including a simple os.system()
call to the sqlite3
utility if you have that installed, but here's roughly what I'd do from Python:
import sqlite3
import csv
con = sqlite3.connect('mydatabase.db')
outfile = open('mydump.csv', 'wb')
outcsv = csv.writer(outfile)
cursor = con.execute('select * from mytable')
# dump column titles (optional)
outcsv.writerow(x[0] for x in cursor.description)
# dump rows
outcsv.writerows(cursor.fetchall())
outfile.close()
这篇关于从 sqlalchemy 转储 csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!