我无法让 Python 的 executemany 使 sqlite3 正常工作 [英] I can't get Python's executemany for sqlite3 to work properly

查看:20
本文介绍了我无法让 Python 的 executemany 使 sqlite3 正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was trying to use executemany to insert values into a database, but it just won't work for me. Here is a sample:

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

这给了我以下错误:

sqlite3.ProgrammingError:提供的绑定数量不正确.当前语句使用1,提供了3个.

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

However, when I change the list, it works fine:

clist = ["a", "b"]
cursor.executemany("INSERT INTO myTable(data) values (?) ", clist)

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

It works as expected! I can see the data in the database. Why does the first list not work and second one does ?

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

(PS: This is just a sample and not the actual code. I made a small test case for simplicity).

推荐答案

据我所知,你的意思是,

From what I know of executemany, you meant,

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

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

Or something similar. Don't quote me on the syntax for sqlite, I haven't used it in an app in a while, but you need an iterable of tuples (more generally iterables).

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

It looks like the error you're getting is that it's trying to iterate through each string you're providing, so your statement works like:

clist = [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i')]

我不知道您的第二个查询要完成什么,但它似乎针对不同的表,所以我猜测没有架构信息,但是如果您将单字符串更改为多字符串,它也会失败.

I don't know what your second query is trying to accomplish, but it appears to address a different table, so I'm guessing off of no schema info, but if you change the single character strings to multicharacter strings, it will fail too.

这篇关于我无法让 Python 的 executemany 使 sqlite3 正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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