简体   繁体   中英

python cx_Oracle Bind illegal variable name

Trouble with bindind date in dictionary in the following statements??

mySQL = 'SELECT day_key FROM timeday WHERE calendar_date =:calendar'
args = {'calendar':'2016/10/16', 'giftcardnbr': '7777083049519090', 'giftcard_amt': '249.8'}

cursor.execute(mySQL,args)

DatabaseError: ORA-01036: illegal variable name/number

Why does this syntax return a different error?

cursor.execute('SELECT day_key FROM timeday WHERE calendar_date =:calendar',{'calendar':'2016/10/16'})

DatabaseError: ORA-01861: literal does not match format string

From mastering Oracle Python

named_params = {'dept_id':50, 'sal':1000}
query1 = cursor.execute('SELECT * FROM employees WHERE department_id=:dept_id AND salary>:sal', named_params)

works fine??

Thanks

Your first query doesn't work because cx_Oracle is trying to bind giftcardnbr and giftcard_amt to non-existent bind variables.

If I bind the correct number of variables in a Cursor.execute() call everything is fine:

>>> import cx_Oracle
>>> DB = cx_Oracle.connect('ben/****@s1/s1')
>>> cur = DB.cursor()
>>> SQL = "select * from dual where 1 = :a"
>>> cur.execute(SQL, {'a' : 1}).fetchall()
[('X',)]

If I try to bind a non-existent variable then it fails with the same error:

>>> cur.execute(SQL, {'a' : 1, 'b' : 2}).fetchall()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
cx_Oracle.DatabaseError: ORA-01036: illegal variable name/number

Your second call fails because '2016/10/16' is not a date, it's a string (see my previous answer Comparing Dates in Oracle SQL ).

If we construct a date and then use that to compare to a date everything's fine:

>>> import datetime
>>> my_date = datetime.datetime(year=2016, month=10, day=16)
>>> my_date
datetime.datetime(2016, 10, 16, 0, 0)
>>> SQL = "select * from dual where date '2016-01-01' = :calendar"
>>> cur.execute(SQL, {'calendar' : my_date }).fetchall()
[]

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