在Python中的SQL语句中绑定非固定变量

时间:2020-07-17 16:34:55

标签: python python-3.x datetime python-sql

我想将不包含固定值的变量绑定到SQL语句中:

示例:

import cx_Oracle
def(var1, var2):
....
  chkdate = datetime.datetime.now().strftime('%d-%m-%Y')
  ....
  cur.execute(query, chkdate)
  ....
  query = """Select * from Table_A where date > :chkdate"""

但这似乎不起作用。我该怎么做?

1 个答案:

答案 0 :(得分:1)

请参阅注释中提到的cx_Oracle绑定doc

如果将日期绑定为字符串,则需要匹配Oracle安装所使用的默认日期格式。相反,您可以直接绑定日期。尝试类似的东西:

with connection.cursor() as cursor:
    chkdate = datetime.datetime.now()
    sql = """select last_name, hire_date from employees where hire_date + (365*13) > :d"""
    for r in cursor.execute(sql, [chkdate]):
        print(r)

数据运算只是因为示例EMPLOYEES表是几年前创建的,而我只想匹配几行。