我在 Python 2.7 sqllite 中有一个简单的单表。我只想将表移植到外部 .csv 文件。
一直在阅读一些教程,他们正在编写大量代码来做到这一点。
似乎这将是一种调用表格('Select * FROM Table')并将其保存到 .csv 的简单方法。
谢谢
您还可以使用 csv 模块进行输出,尤其是当您的字符串字段包含逗号时。
#!/usr/bin/python3
import sqlite3
connection = sqlite3.connect('example_database')
cursor = connection.cursor()
cursor.execute('drop table example_table')
cursor.execute('create table example_table(string varchar(10), number int)')
cursor.execute('insert into example_table (string, number) values(?, ?)', ('hello', 10))
cursor.execute('insert into example_table (string, number) values(?, ?)', ('goodbye', 20))
cursor.close()
cursor = connection.cursor()
cursor.execute('select * from example_table')
for row in cursor.fetchall():
print('{},{}'.format(row[0], row[1]))
cursor.close()
connection.close()