Python 带参数的 SQlite3 插入
Python SQlite3 insert with params
问题:
我在使用 python 向 SQlite 中插入数据时遇到问题。目前我是 python 的新手,所以这一定是初学者的错误。
错误:
OperationalError: unrecognized token: "{"
我试过的:
我已经阅读了很多教程并尝试了很多选项,如下面的代码所示 examples.But 由于某种原因,我无法正常工作。
一些例子:
cursor.execute("INSERT INTO wanted_movie (tmdb_id, name, year) VALUES ({tmdb_id}, {name}, {year})".format(
tmdb_id=str(data['id']), name=str(data['title']), year=str(data['release_date']).split('-')[0]))
cursor.execute("INSERT INTO wanted_movie (tmdb_id, name, year) VALUES ({tmdb_id}, {name}, {year})", {
"tmdb_id": str(data['id']), "name": str(data['title']), "year": str(data['release_date']).split('-')[0]})
conn.commit()
问题:
谁能帮我用 SQlite3 以 pythonic 方式正确插入一行?
不仅仅是 pythonic 方式还有 sqlitic 方式
来自docs
Instead, use the DB-API’s parameter substitution. Put ? as a placeholder wherever you want to use a value, and then provide a tuple of values as the second argument to the cursor’s execute()
method.
你的一个例子可以用
解决
values = (data['id'],data['title'],data['release_date'])
cursor.execute("INSERT INTO wanted_movie (tmdb_id, name, year) VALUES (?, ?, ?)",values)
问题:
我在使用 python 向 SQlite 中插入数据时遇到问题。目前我是 python 的新手,所以这一定是初学者的错误。
错误:
OperationalError: unrecognized token: "{"
我试过的:
我已经阅读了很多教程并尝试了很多选项,如下面的代码所示 examples.But 由于某种原因,我无法正常工作。
一些例子:
cursor.execute("INSERT INTO wanted_movie (tmdb_id, name, year) VALUES ({tmdb_id}, {name}, {year})".format(
tmdb_id=str(data['id']), name=str(data['title']), year=str(data['release_date']).split('-')[0]))
cursor.execute("INSERT INTO wanted_movie (tmdb_id, name, year) VALUES ({tmdb_id}, {name}, {year})", {
"tmdb_id": str(data['id']), "name": str(data['title']), "year": str(data['release_date']).split('-')[0]})
conn.commit()
问题:
谁能帮我用 SQlite3 以 pythonic 方式正确插入一行?
不仅仅是 pythonic 方式还有 sqlitic 方式
来自docs
Instead, use the DB-API’s parameter substitution. Put ? as a placeholder wherever you want to use a value, and then provide a tuple of values as the second argument to the cursor’s
execute()
method.
你的一个例子可以用
解决values = (data['id'],data['title'],data['release_date'])
cursor.execute("INSERT INTO wanted_movie (tmdb_id, name, year) VALUES (?, ?, ?)",values)