python - Django cursor.executemany 参数

标签 python mysql django

我使用 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’s execute() 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 不会在我这边发出任何警告。您可能做了一些不同的事情:

enter image description here

关于python - Django cursor.executemany 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37011086/

相关文章:

java - Hibernate不创建表

django - 如何获取haystack搜索中搜索结果的数量?

python - 如何处理 Django 中未应用的迁移?

python - Django 中每个客户(通过迭代)的订单值(value)计数和总和

python - 数字代码回归测试框架

python - 视频捕捉 : Capture Graph Error

python - Pandas:将列表从列值映射到列?

python - 检查列表是否是子列表

MySQL 触发器获取导致触发器触发的当前查询

PHP和mysql字符集问题