简体   繁体   English

将python列表插入SQLite3列

[英]Insert python list into SQLite3 column

I have three python lists with about 1.5 million entries each and would like to insert these into a new SQLite table. 我有三个Python列表,每个列表约有150万个条目,并希望将它们插入新的SQLite表中。 When doing this I get the error: 这样做时,我得到错误:

OperationalError: no such column: days OperationalError:无此类列:天

This is the code I have: 这是我的代码:

con = sqlite3.connect('database.db')
cur = con.cursor()
...
cur.execute("DROP TABLE IF EXISTS days")
cur.execute("CREATE TABLE IF NOT EXISTS days(DAYS_NEEDED integer, RAISED_TIME text, POSTED_TIME text)")
cur.execute("INSERT INTO days (DAYS_NEEDED, RAISED_TIME, POSTED_TIME) VALUES (days, rt_list, pt_list)")
con.commit()

"days" is a list of integers, rt_list and pt_list are both lists of strings. “ days”是一个整数列表,rt_list和pt_list都是字符串列表。 Does anyone know what I'm doing wrong here? 有人知道我在做什么错吗?

Any help is much appreciated! 任何帮助深表感谢!

You have to use ? 你要用? placeholders inside your VALUES() and then provide the actual values to the execute method. VALUES()占位符,然后将实际值提供给execute方法。 Something along the lines should do the job: 可以做一些事情:

con = sqlite3.connect('database.db')
cur = con.cursor()
...
cur.execute("DROP TABLE IF EXISTS days")
cur.execute("CREATE TABLE IF NOT EXISTS days(DAYS_NEEDED integer, RAISED_TIME text, POSTED_TIME text)")

def insert(days_needed, rt, pt):
    cur.execute("INSERT INTO days (DAYS_NEEDED, RAISED_TIME, POSTED_TIME) VALUES (?, ?, ?)", (days_needed, rt, pt))

for d, rt, pt in zip(days, rt_list, pt_list):
    insert(d, rt, pt)

con.commit()

That's not the way you can insert list of values in SQL. 这不是您可以在SQL中插入值列表的方式。 First, you must give a valid SQL instruction using ? 首先,您必须使用?给出有效的SQL指令? as placeholders. 作为占位符。 Then if you want to insert more than one row at a time, you will need the executemany method. 然后,如果您想一次插入多个行,则需要executemany方法。 It is a true improvement because the SQL in only parsed and prepared once. 这是真正的改进,因为SQL仅解析和准备一次。

So you should have written: 所以你应该写:

cur.execute("DROP TABLE IF EXISTS days")
cur.execute("CREATE TABLE IF NOT EXISTS days(DAYS_NEEDED integer, RAISED_TIME text, POSTED_TIME text)")
cur.executemany("INSERT INTO days (DAYS_NEEDED, RAISED_TIME, POSTED_TIME) VALUES (?,?,?)",
                zip(days, rt_list, pt_list))
con.commit()

BTW, the direct usage of zip is a Sqlite3 module extension, the DB-API 2.0 Python interface normally requires a sequence where zip returns an iterator , so the more portable way (any DB engine) would be: 顺便说一句, zip的直接用法是Sqlite3模块扩展,DB-API 2.0 Python接口通常需要一个序列 ,其中zip返回一个迭代器 ,因此,更可移植的方式(任何DB引擎)将是:

cur.executemany("INSERT INTO days (DAYS_NEEDED, RAISED_TIME, POSTED_TIME) VALUES (?,?,?)",
                tuple(zip(days, rt_list, pt_list)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM