【问题标题】:Python cx_Oracle binding in SQL query gives ORA-01036: illegal variable name/numberSQL 查询中的 Python cx_Oracle 绑定给出 ORA-01036:非法变量名称/编号
【发布时间】:2021-02-13 16:33:17
【问题描述】:

我想编写一个通过 SQL 查询返回 pandas DataFrame 的函数。 我有 4 个 agruments,最后 2 个是“查询”本身和“date_of_report”。

这是查询结构:

practice_query = """select * from <TABLE_NAME> b
        where b.VALUE_DATE = TO_DATE(:date_of_report,'yyyy-mm-dd') """

我的功能:

import time
import cx_Oracle
import pandas as pd

def my_query(username: str = "USERNAME",
              password: str = "PASSWORD",
              query: str = "",
              date_of_report: str = "") -> pd.DataFrame: 

    
    start = time.perf_counter()
    
    # create connection ot EDW tables
    dsn = cx_Oracle.makedsn("....", \
                             1112, \
                             service_name = "...")

    conn = cx_Oracle.connect(username, password, dsn, encoding="UTF-8")

    # create cursor
    cur = conn.cursor()

    cur.execute(query, date_of_report)
    col_names = [row[0] for row in cur.description]
    mydata = pd.DataFrame(cur.fetchall())
    
    mydata.columns = col_names
    
    end = time.perf_counter() - start
    print("Run time: {:.3f}s".format(end))
    
    return mydata

我的函数调用:

mydata = edw_query(query = practice_query, date_of_report = "2020-09-30")

这是我的错误信息:


DatabaseError                             Traceback (most recent call last)
<ipython-input-22-0ecdc646fe92> in <module>
----> 1 mydata = edw_query(query = practice_query, date_of_report = '"2020-09-30"')

<ipython-input-8-c7875fbe0d2a> in edw_query(username, password, query, date_of_report)
     36     cur = conn.cursor()
     37 
---> 38     cur.execute(query, date_of_report)
     39     col_names = [row[0] for row in cur.description]
     40     mydata = pd.DataFrame(cur.fetchall())

DatabaseError: ORA-01036: illegal variable name/number

您能帮忙找出正确的语法吗?我在 SQL 文本中尝试过 date ':date_of_report',其中 date_of_report = "2020-09-30",我也尝试过:date_of_report where date_of_report = '"2020-09-30"',但似乎没有任何效果.

我找到了这些,但找不到方法:

https://cx-oracle.readthedocs.io/en/latest/user_guide/bind.html

https://www.techonthenet.com/oracle/functions/to_date.php

非常感谢: 罗兰

【问题讨论】:

    标签: python sql date cx-oracle


    【解决方案1】:

    将执行绑定参数改为:

        cur.execute(query, [date_of_report])
    

        cur.execute(query, date_of_report=date_of_report)
    

    请参阅 cx_Oracle 手册部分Using Bind Variables。如果您对改进此文档有任何建议,请告诉我们。

    【讨论】:

    • 亲爱的 Christopher,感谢您的帮助,它现在可以正常工作了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-06
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 2016-04-03
    • 1970-01-01
    相关资源
    最近更新 更多