将cx_Oracle与IN语句一起使用(Python 3)

时间:2018-09-06 16:44:48

标签: python python-3.x oracle cx-oracle bind-variables

我正在尝试使用cx_Oracle将参数传递到SQL“ IN”语句中。这样可以得出正确的结果:

sql = """select * from
           (select level numb from dual connect by level <= 4)
         where numb = :var"""

print([row[0] for row in cur.execute(sql, (1,))])
Output: [1]

但是我还无法弄清楚如何使用“ IN”语句。

sql = """select * from
           (select level numb from dual connect by level <= 4)
         where numb in :var"""

print([row[0] for row in cur.execute(sql, (1, 2))])
Output: cx_Oracle.DatabaseError: ORA-01036: illegal variable name/number

我尝试了IN语句的变体,还尝试使用字典来传递参数。

1 个答案:

答案 0 :(得分:0)

使用单个值或文字时,SQL中的IN子句需要用括号括起来的值。而且,由于您传递了两个参数,因此在括号内要包含两个占位符。

sql = """select * from
           (select level numb from dual connect by level <= 4)
         where numb in (:1, :2)"""

print([row[0] for row in cur.execute(sql, (1, 2))])