简体   繁体   中英

How to fix syntax error with UPDATE in SQLite3 Python module

I'm using python module sqlite3 as per the below code:

# 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. 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 =?

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 =? 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 ? 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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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