使用Python将CSV文件导入sqlite3数据库表

使用Python将CSV文件导入sqlite3数据库表

问题描述:

我有一个CSV文件,我想使用Python批量导入这个文件到我的sqlite3数据库。该命令是.import .....。但似乎它不能像这样工作。任何人都可以给我一个例子,如何在sqlite3?我使用windows,以防万一。
感谢

I have a CSV file and I want to bulk-import this file into my sqlite3 database using Python. the command is ".import .....". but it seems that it cannot work like this. Can anyone give me an example of how to do it in sqlite3? I am using windows just in case. Thanks



import csv, sqlite3

con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("CREATE TABLE t (col1, col2);") # use your column names here

with open('data.csv','rb') as fin: # `with` statement available in 2.5+
    # csv.DictReader uses first line in file for column headings by default
    dr = csv.DictReader(fin) # comma is default delimiter
    to_db = [(i['col1'], i['col2']) for i in dr]

cur.executemany("INSERT INTO t (col1, col2) VALUES (?, ?);", to_db)
con.commit()
con.close()