如何使用executemany将每个Key中的第一个值写入数据库 [英] How do I use executemany to write the first values in each Key to a database

查看:52
本文介绍了如何使用executemany将每个Key中的第一个值写入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,正在尝试使用for循环通过使用cursor.executemany()函数从字典中的列表到数据库依次添加第一个和后续值.

I am new to Python and am trying to use a for loop to add the first and subsequent values, sequentially from a list within a dictionary to a database by using the cursor.executemany() function.

这是我的代码

dict = {'yo': [1,2,3,4,5,6,7],'meh':[1,2,3,4,5,6,7],'blah':[1,2,3,4,5,6,7]}

conn = sqlite3.connect('tester.db')
cur = conn.cursor()

cur.executescript('''
DROP TABLE IF EXISTS;

CREATE TABLE Numbers (
    id  INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    yo  INTEGER,
    meh INTEGER,
    blah    INTEGER
);

''')

for key,val in dict.items():
    i = 0

    cur.executemany('''INSERT OR IGNORE INTO Number_game (yo,meh,blah)
    VALUES (?,?,?)''', (val(i))
    i = i+1                     
    conn.commit()

在i = i + 1迭代中,我不断收到语法错误.我正在尝试将所有1都添加到第一行,然后将2添加,依此类推.有人可以告诉我我在做什么错吗?感觉就像是一个明显的错误,我无法弥补.

I keep getting a syntax error on the i = i+1 iteration. I am trying to add all the 1's to the first row, then the 2's and so on. Can someone tell me what I am doing wrong? it feels like a glaring mistake im unable to pick up.

提前谢谢.

推荐答案

executemany想要一个元组列表,每个元组包含一行,即,一个元素来自yo,一个元素来自meh,另一个元素来自blah.那不是 .items()所提供的,因为它会在每次迭代中提供一个键以及与该键关联的值.

executemany wants a list of tuples each one containing one row, that is, one element from yo, one from meh, and one from blah. That is not what .items() provide, since it will provide a key and the values associated with that key on each iteration.

幸运的是 zip()函数完全满足您的需求:

Luckly the zip() function does exactly what you need:

cur.executemany('...insert...', zip(my_dict['yo'], my_dict['meh'], my_dict['blah']))

这篇关于如何使用executemany将每个Key中的第一个值写入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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