cx\ U Oracle在更新表时执行/执行错误

2024-03-28 21:36:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从Python代码中有条件地更新Oracle表。这是一段简单的代码,但我遇到了cx\u Oracle.DatabaseError:ORA-01036:非法变量名/编号,尝试如下

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,…”语法(但另一方面,我还没有找到任何更新和cx_Oracle的示例)。虽然我的问题在字典的帮助下得到了解决,但我想知道这是一种常见的更新方式,还是我在“:1,:2,…”语法中做错了什么

Oracle 12c、Python 3.7、cx_Oracle 7.2.1


Tags: ofinidsqlaswithtableupdate
1条回答
网友
1楼 · 发布于 2024-03-28 21:36:57

您确实可以绑定字典,但创建字典的开销可能是不可取的。您需要确保在使用executemany()时创建序列列表。因此,在您的情况下,您需要这样的内容:

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

首先,您有一个字符串列表。字符串本身就是序列,因此在这种情况下,cx_Oracle需要4个绑定变量(每个字符串中的字符数)

在第二个实例中,您拥有与第一个实例相同的数据,因为您只是在字符串周围包含括号,而不是创建元组!您需要如我的示例中所示的尾随逗号来创建元组,正如您所认为的那样

相关问题 更多 >