在python sqlite3模块中导入数据文件(如.csv)的任何其他方法? [不一一插入] [英] Any other way to import data files(like .csv) in python sqlite3 module ? [not insert one by one]
问题描述
在sqlite3的客户端CLI中,有.import文件TABLE_name来执行此操作。
In sqlite3's client CLI, there is " .import file TABLE_name " to do it.
但是,我不想将sqlite3安装到我的服务器上。
But, I do not want to install sqlite3 to my server at present.
在python sqlite3模块中,我们可以创建和编辑数据库。
In python sqlite3 module, we can creat and edit a DB.
但是,我还没有找到将数据文件导入TABLE的方法,
除了逐行插入行外。
But, I have not found a way to import data-file to a TABLE, except inserting rows one by one.
还有其他方法吗?
推荐答案
您可以使用 executemany 命令,而不是一个一个地插入
You could insert at one shot using executemany command instead of inserting one by one
假设我有users.csv与以下内容
Lets say I have users.csv with following contents
"Hugo","Boss"
"Calvin","Klein"
并且基本上用csv模块打开并将其传递给.executemany函数
and basically open with csv module and pass it to .executemany function
import csv,sqlite3
persons= csv.reader(open("users.csv"))
con = sqlite3.connect(":memory:")
con.execute("create table person(firstname, lastname)")
con.executemany("insert into person(firstname, lastname) values (?, ?)", persons)
for row in con.execute("select firstname, lastname from person"):
print row
#(u'Hugo', u'Boss')
#(u'Calvin', u'Klein')
这篇关于在python sqlite3模块中导入数据文件(如.csv)的任何其他方法? [不一一插入]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!