SQL 在 Django 中将 format() 函数与 pyodbc 一起使用时出错

SQL error when using format() function with pyodbc in Django

我想在我的 Django 应用程序中使用 pyodbc 执行命令。当我对一列进行简单更新时效果很好:

cursor.execute("UPDATE dbo.Table SET attr = 1 WHERE id = {}".format(id))

然而,当我尝试使用字符串作为列值时,它会抛出错误:

cursor.execute("UPDATE dbo.Table SET attr = 1, user = '{}' WHERE id = {}".format(id, str(request.user.username)))

错误信息如下:

('42S22', "[42S22] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid column name 'Admin'. (207) (SQLExecDirectW)")

令人惊讶的是这个方法有效:

cursor.execute("UPDATE dbo.Table SET attr = 1, user = 'Admin' WHERE id = {}".format(id))

好像是什么问题?为什么 sql 将列值误认为是它的名称?

您的格式参数反了。您将 id 传递给用户,将用户名传递给 id WHERE 子句。

如上所述,您的参数是反的,但如果您要使用 cursor.execute(),更重要的是使用位置参数 (%s)。这会将 SQL 和值分别传递到数据库后端,并保护您免受 SQL 注入:

from django.db import connection

cursor = connection.cursor()

cursor.execute("""
    UPDATE dbo.Table
    SET attr = 1,
        user = %s
    WHERE id = %s
""", [
    request.user.username,
    id,
])