我不能让Python的executemany让sqlite3正常工作

bra*_*ter 14 python sqlite pysqlite

我试图使用executemany将值插入数据库,但它对我不起作用.这是一个示例:

clist = []
clist.append("abc")
clist.append("def")
clist.append("ghi")
cursor.executemany("INSERT INTO myTable(data) values (?) ", clist)
Run Code Online (Sandbox Code Playgroud)

这给了我以下错误:

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 3 supplied.

但是,当我更改列表时,它工作正常:

clist = ["a", "b"]
cursor.executemany("INSERT INTO myTable(data) values (?) ", clist)
Run Code Online (Sandbox Code Playgroud)

它按预期工作!我可以在数据库中看到数据.为什么第一个列表不起作用而第二个列表不起作用?

(PS:这只是一个示例,而不是实际代码.为简单起见,我做了一个小测试用例).

mar*_*r75 16

根据我所知的executemany,你的意思是,

clist = [("abc", ), ("def", ), ("ghi", )]
cursor.executemany("INSERT INTO myTable(data) values(?)", clist)
Run Code Online (Sandbox Code Playgroud)

或类似的东西.不要引用我的sqlite语法,我有一段时间没有在应用程序中使用它,但你需要一个可迭代的元组(更常见的是iterables).

看起来你得到的错误是它试图遍历你提供的每个字符串,所以你的语句就像:

clist = [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i')]
Run Code Online (Sandbox Code Playgroud)

我不知道你的第二个查询试图完成什么,但它似乎解决了一个不同的表,所以我猜测没有架构信息,但如果你将单个字符串更改为多字符串,它也会失败.

  • 在executemany之后,需要conn.commit()来更新表。 (2认同)

bos*_*ssi 7

只是为了补充上下文:在一个密切相关的情况下,我打算使用这样的方式将多元组列表插入到表中executemany:

res = [("John", "2j4o1h2n"), ("Paula", "lsohvoeemsy"), ("Ben", "l8ers")]

cur.executemany("INSERT INTO users (user, password) VALUES (?)", res)
Run Code Online (Sandbox Code Playgroud)

期望SQLite一次获取一个元组(因此VALUES字段中的单个 ?参数替换)并将其拆分为其封装属性(<username>, <password>在本例中),它也会因sqlite3.ProgrammingError异常The current statement uses 1, and there are 2 supplied.而失败,因为SQLite期望单独替换属性在VALUES (...)现场.所以这解决了它:

cur.executemany("INSERT INTO users (user, password) VALUES (?, ?)", res)
Run Code Online (Sandbox Code Playgroud)

这是一个微不足道的案例,但可能会有点混淆,我希望它可以帮助那些被困的人.