cx_oracle缺少右括号

时间:2018-09-20 17:12:59

标签: python sql select cx-oracle

我正在使用cx_oracle python库查找最近90分钟内所有具有ModifyDate的记录。

import cx_Oracle
import datetime
from datetime import timedelta
import config as config

timeNow = datetime.datetime.now()
previousTime = timeNow - datetime.timedelta (minutes = 0)
connection = cx_Oracle.connect(user, password, connection)
cur = connection.cursor()
statement = "SELECT * FROM woodburn_all WHERE modifiedDate >= to_date(" + str(previousTime) +")"
print statement
r = cur.execute(statement)
for row in cur:
    print row

打印的选择语句看起来正确:

SELECT * FROM woodburn_all WHERE to_date(modifiedDate) >= to_date(2018-09-2 11:02:10.460000)

我没有在哪里遗漏任何括号。这是一些奇怪的日期/时间吗?

编辑:使用Python v2.7

2 个答案:

答案 0 :(得分:0)

your problem in sql statement where clause
 to_date(2018-09-2 11:02:10.460000)

因为您是用oracle编写的

select  to_date(2018-09-2 11:02:10.460000) from dual this will trrow
  1. ORA-00907:缺少右括号,当任何sql语句语法错误发生时oracle引擎抛出此错误

所以会是这样

select TO_DATE('09/02/2018 13:27:18', 'MM/DD/YYYY HH24:MI:SS') from dual

所以您的where子句将

TO_DATE('09/02/2018 13:27:18', 'MM/DD/YYYY HH24:MI:SS')

答案 1 :(得分:0)

从根本上讲,您正在将未加引号的字符串项传递给Oracle查询。正如@TheImpaler在评论中提到的,只需使用parameterization即可处理引号和文字。

此外,使用strftime将datetime对象转换为所需的字符串格式。实际上,您不需要减去分钟:

time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')

# PREPARED STATEMENT
statement = "SELECT * FROM woodburn_all WHERE modifiedDate >= to_date(:1, :2)"

# PASSING TUPLE OF PARAMS
r = cur.execute(statement, (time_now, 'YYYY-MM-DD HH24:MI'))

for row in r:
    print(row)