在to_date函数中使用cx_oracle变量时无法正确绑定

时间:2018-07-30 04:19:40

标签: python-2.7 data-binding cx-oracle

我正尝试替换此呼叫:

cursor = connection.cursor()
try:
    sql = "select m.lat, m.longt, v.tmax from vcsn_view v, vcsn_metadata m where set_vcsn('local_day=to_date(20180304)-1') is null and v.agent_no = m.agent_no(+) order by 1,2"
    cursor.execute(sql)
    for lat, longt, tmax in cursor:
        print("Values:", lat, longt, tmax)
except cx_Oracle.DatabaseError, e:
    printf ('Failed to select\n')
    printException(e)
    exit(1)

带有将查询中的日期作为变量的调用,即:

cursor = connection.cursor()
try:
    sql = "select m.lat, m.longt, v.tmax from vcsn_view v, vcsn_metadata m where set_vcsn('local_day=to_date(:1)-1') is null and v.agent_no = m.agent_no(+) order by 1,2"
    cursor.execute(sql, (20180304,))
    for lat, longt, tmax in cursor:
        print("Values:", lat, longt, tmax)
except cx_Oracle.DatabaseError, e:
    printf ('Failed to select\n')
    printException(e)
    exit(1)

但是我无法使其正常工作。我收到错误消息:
    选择失败     错误代码= 1036     错误消息= ORA-01036:无效的变量名称/编号

1 个答案:

答案 0 :(得分:0)

在您的SQL中,您使用:1内引号使它无法工作。我不确定set_vcsn()是否需要字符串。假设确实如此,您需要执行以下操作:cursor = connection.cursor()

try:
    sql = "select m.lat, m.longt, v.tmax from vcsn_view v, vcsn_metadata m where set_vcsn('local_day=to_date(' || :1 || ')-1') is null and v.agent_no = m.agent_no(+) order by 1,2"
    cursor.execute(sql, (20180304,))
    for lat, longt, tmax in cursor:
        print("Values:", lat, longt, tmax)
except cx_Oracle.DatabaseError, e:
    printf ('Failed to select\n')
    printException(e)
    exit(1)

如果set_vcsn()不需要字符串,那么如果需要进一步的帮助,提供更多的信息将很有帮助。但是通常,不会在字符串中的值中搜索绑定变量!