简体   繁体   English

如何使用 SQLite3 Python 模块中的 UPDATE 修复语法错误

[英]How to fix syntax error with UPDATE in SQLite3 Python module

I'm using python module sqlite3 as per the below code:我正在按照以下代码使用 python 模块 sqlite3:

# Enter the randomised data into the dictionary:
for square in cube:
    cur.execute("UPDATE cubes SET ? = ? WHERE id = ?", (square, cube[square], session["current_cube_id"]))
con.commit()

Which results in the following error:这会导致以下错误:

cur.execute("UPDATE cubes SET ? = ? WHERE id = ?", (square, cube[square], session["current_cube_id"]))
sqlite3.OperationalError: near "?": syntax error

I don't seem to have a problem with INSERT or SELECT queries, so I assume there is a specific syntax required to UPDATE.我似乎对 INSERT 或 SELECT 查询没有问题,所以我假设 UPDATE 需要特定的语法。 From the documentation, tutorials and other examples I can find this seems to be correct - can anyone please assist with what might be the syntax error?从文档、教程和其他示例中,我发现这似乎是正确的 - 任何人都可以帮助解决可能的语法错误吗?

You can't define table, column names, or SQL keywords, using bind variables (the SET? = ) in UPDATE cubes SET? =? WHERE id =?您不能在UPDATE cubes SET? =? WHERE id =? SET? = UPDATE cubes SET? =? WHERE id =?

I am not sure why you feel you need to have a dynamic column name, rather than UPDATE cubes SET mycol =? WHERE id =?我不知道为什么你觉得你需要一个动态列名,而不是UPDATE cubes SET mycol =? WHERE id =? UPDATE cubes SET mycol =? WHERE id =? but you need to specify your column name differently.但您需要以不同的方式指定列名。

You'd have the exact same problem with insert or delete if your target column names, in an insert, or your where condition column names in a delete, were getting specified with ?如果插入或删除中的目标列名或删除中的 where 条件列名被指定为? placeholders.占位符。 I assume you did not do this so you did not get the error.我假设你没有这样做,所以你没有得到错误。

Be very careful if you decide to build your query string dynamically as in如果您决定动态构建查询字符串,请务必小心,如

myquery = f"UPDATE cubes SET {my_user_supplied_column_name} = ? WHERE id = ?"

cur.execute(myquery, (cube[square], session["current_cube_id"]))

That opens you to a large class of extremely serious vulnerabilities, the SQL Injections because the user may enter anything they want in my_user_supplied_column_name .这会让您看到一个包含极其严重漏洞的大型 class,即SQL 注入,因为用户可以在my_user_supplied_column_name中输入他们想要的任何内容。 Best to be very careful as it also has a reputational risk: a savvy prospective employer might for example reject your application if they saw this type of construct, unguarded, in your code because it is an extremely grave, frequent and well-known risk.最好非常小心,因为它也有声誉风险:例如,如果一个精明的潜在雇主在您的代码中看到这种类型的结构,没有保护,可能会拒绝您的申请,因为这是一个极其严重、频繁和众所周知的风险。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM