【发布时间】: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
非常感谢: 罗兰
【问题讨论】: