我使用 Django cursor.execuremany 有一段时间了,我想做一些准备工作。
在这个 Stackoverflow 页面上,我读到使用字符串格式化运算符和问号是个坏主意。 How to use variables in SQL statement in Python?
然而,当我在我的程序中使用它时,我得到一个错误:
TypeError: not all arguments converted during string formatting
这是我写的代码:
from django.db import connection
values = ((1, "john"), (2, "robert"), (3, "angela"))
cursor = connection.cursor()
query = "REPLACE INTO names (id, name) VALUES (?, ?)"
cursor.executemany(query, values)
当我仅将 ?
替换为 %s
时,它会按预期工作。
另一件事(让我开始搜索)是 PyCharm 在使用 %s
时给我一个错误。
<expression> expedted, got %
这不是主要问题,但我不确定这是否会有所作为。
我在用什么
- python 2.7
- Django 1.4
- MySql
最佳答案
When I only replace the ? with %s it works as expected.
?
占位符用于 SQLite仅:
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’sexecute()
method. (Other database modules may use a different placeholder, such as%s
or:1
.)
MySQL 驱动程序希望将 %s
视为查询参数占位符:
query = "REPLACE INTO names (id, name) VALUES (%s, %s)"
cursor.executemany(query, values)
Another thing (that got me started searching) is that PyCharm is giving me an error when using %s.
PyCharm 不会在我这边发出任何警告。您可能做了一些不同的事情:
关于python - Django cursor.executemany 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37011086/