您正在滥用绑定。
使用cx_Oracle绑定变量有三种不同的方式,可以在这里看到:
1)通过将元组传递给带有 编号变量 的SQL语句:
sql = "select * from sometable where somefield = :1 and otherfield = :2"cur.execute(sql, (aValue, anotherValue))
2)通过将关键字参数传递给 带有命名变量 的SQL语句:
sql = "select * from sometable where somefield = :myField and otherfield = :anotherOne"cur.execute(sql, myField=aValue, anotherOne=anotherValue)
3)通过将字典传递给 带有命名变量 的SQL语句:
sql = "select * from sometable where somefield = :myField and otherfield = :anotherOne"cur.execute(sql, {"myField":aValue, "anotherOne":anotherValue})备注
那么为什么您的代码起作用?
让我们尝试了解这里发生的情况:
bind= {"var" : "ciao"}sql = "select * from sometable where somefield = :bind and otherfield = :bind"cur.execute(sql,(bind["var"], bind["var"]))Oracle将理解它期望一个变量。这是一个命名变量,由name链接
bind。然后,您应该像这样给一个参数作为命名参数:
cur.execute(sql, bind="ciao")
或使用字典,像这样:
cur.execute(sql, {bind:"ciao"})但是,由于cx_Oracle接收到一个元组,它会回退到按数字的绑定中,就像您的SQL语句是:
sql = "select * from sometable where somefield = :1 and otherfield = :2"
当您传递
bind['var']两次时,这只是字符串
"ciao"。它将两个元组项映射到编号的变量:
cur.execute(sql, ("ciao", "ciao"))那是偶然的,但是代码很容易让人误解。
具有单个值的元组绑定
还要注意,第一个选项需要一个元组。但是,如果您要绑定单个值,则可以使用此表示法创建单个值的元组:
sql = "select * from sometable where somefield = :1"cur.execute(sql, (aValue,))
[编辑]:感谢@ tyler-christian提到cx_Oracle支持传递命令。



