我正在尝试获取在python中创建的元组列表,并将它们导入到SQLite中的表中.以下代码有效:
conn = sqlite3.connect('emaildb4.sqlite') cur = conn.cursor() cur.execute('''CREATE TABLE Counts (email TEXT, count INTEGER)''')
但是,一旦我尝试插入字典,看起来像这样,并被调用Counts
:
[('txstate.edu', 17), ('media.berkeley.edu', 56), ('vt.edu', 110), ('whitman.edu', 17), ('lancaster.ac.uk', 14), ('rsmart.com', 8), ('fhda.edu', 1), ('uct.ac.za', 96), ('unicon.net', 9), ('utoronto.ca', 1), ('loi.nl', 9), ('indiana.edu', 178), ('et.gatech.edu', 17), ('umich.edu', 491), ('gmail.com', 25), ('ucdavis.edu', 1), ('stanford.edu', 12), ('bu.edu', 14), ('caret.cam.ac.uk', 157), ('ufp.pt', 28), ('iupui.edu', 536)]
使用以下代码,我只获得了一个Out[318]:
,而且没有在SQLite表中进行任何更改.
码:
cur.executemany('insert into Counts (email, count) values (?,?)',Counts)
我也尝试将元组更改为字典/按名称引用值,并循环遍历运行cur.execute的列表多次.
您需要提交更改:
cur.executemany('insert into Counts (email, count) values (?,?)',Counts) conn.commit()
您可以通过将其用作上下文管理器来自动处理此连接:
with conn: cur.executemany('insert into Counts (email, count) values (?,?)',Counts)