【发布时间】:2023-03-28 08:15:01
【问题描述】:
我需要从我的 Python 代码有条件地更新 Oracle 表。这是一段简单的代码,但我遇到了 cx_Oracle.DatabaseError: ORA-01036: invalid variable name/number 并尝试了以下
id_as_list = ['id-1', 'id-2'] # list of row IDs in the DB table
id_as_list_of_tuples = [('id-1'), ('id-2')] # the same as list of tuples
sql_update = "update my_table set processed = 1 where object_id = :1"
# then when I tried any of following commands, result was "illegal variable name/number"
cursor.executemany(sql_update, id_as_list) # -> ends with error
cursor.executemany(sql_update, id_as_list_of_tuples) # -> ends with error
for id in id_as_list:
cursor.execute(sql_update, id) # -> ends with error
正确的解决方案是在 SQL 语句中使用字典列表和键名:
id_as_list_of_dicts = [{'id': 'id-1'}, {'id': 'id-2'}]
sql_update = "update my_table set processed = 1 where object_id = :id"
cursor.executemany(sql_update, id_as_list_of_dicts) # -> works
for id in id_as_list_of_dicts:
cursor.execute(sql_update, id) # -> also works
我找到了一些帮助和教程,例如this,它们都使用“:1, :2,...”语法(但另一方面,我没有找到任何关于 update 和 cx_Oracle 的示例)。虽然我的问题已经在字典的帮助下得到了解决,但我想知道这是否是常见的更新方式,或者我是否在 ":1, :2,..." 语法中做错了什么。
Oracle 12c、Python 3.7、cx_Oracle 7.2.1
【问题讨论】:
-
你的绑定没问题。您可能还需要预定义内存,如cx-oracle.readthedocs.io/en/latest/user_guide/… 所示