使用 iteritems() 将字典插入到 sqlite3 数据库中
我的“video_episodes”表就像:
CREATE TABLE "video_episodes" (
"id" integer NOT NULL PRIMARY KEY,
"dizilink_id" integer NOT NULL REFERENCES "video_dizilink" ("id"),
"episodename" varchar(50) NOT NULL,
"episodeurl" varchar(200) NOT NULL);
我试图在字典中插入一些值:
video_links = {'a': '1', 'b': '2'}
cursor.executemany("""INSERT INTO video_episodes(dizilink_id, episodename, episodeurl) VALUES (?,?,?)""", dizilink_id, video_links.iteritems(),)
TypeError: function takes exactly 2 arguments (3 given)
如果没有 dizilink_id,我可以使用 iteritems() 插入,但我无法理解如何使用附加键来插入。
My "video_episodes" table is like:
CREATE TABLE "video_episodes" (
"id" integer NOT NULL PRIMARY KEY,
"dizilink_id" integer NOT NULL REFERENCES "video_dizilink" ("id"),
"episodename" varchar(50) NOT NULL,
"episodeurl" varchar(200) NOT NULL);
I'm trying to insert some values within a dict:
video_links = {'a': '1', 'b': '2'}
cursor.executemany("""INSERT INTO video_episodes(dizilink_id, episodename, episodeurl) VALUES (?,?,?)""", dizilink_id, video_links.iteritems(),)
TypeError: function takes exactly 2 arguments (3 given)
Without dizilink_id, I'm able to insert with iteritems() but I can't understand how it's possible with additional key(s).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这与 iteritems 无关。
正如错误消息所示,
executemany
(为什么使用 Many,而不是简单的execute
?)需要两个参数,而您传递了三个参数。 SQL 语句的参数是单个参数,因此需要包装在元组中。评论后编辑 好的,我想我明白你现在想要做什么。您想要为 dizilink_id 的相同值插入多个(episodename、episodeurl)值。
你不能用executemany 做到这一点。您需要运行多个命令。像这样的东西:
This has nothing to do with iteritems.
As the error message says,
executemany
(why are you using many, rather than simpleexecute
?) takes two arguments, and you are passing three. The parameters to the SQL statement are a single parameter, so need to be wrapped in a tuple.Edit after comment OK, I think I understand what you are trying to do now. You want to insert multiple values of (episodename, episodeurl) for the same value of dizilink_id.
You can't do that with executemany. You'll need to run multiple commands. Something like this: