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

2021-12-05 00:00:00 python csv database sqlite

我有一个 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:") # change to 'sqlite:///your_filename.db'
cur = con.cursor()
cur.execute("CREATE TABLE t (col1, col2);") # use your column names here

with open('data.csv','r') 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()

相关文章