使用 Python 将 CSV 文件导入 sqlite3 数据库表 [英] Importing a CSV file into a sqlite3 database table using Python

查看:57
本文介绍了使用 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:") # 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()

这篇关于使用 Python 将 CSV 文件导入 sqlite3 数据库表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆