Shoonya
Shoonya

Reputation: 128

python oracle where clause containing date greater than comparison

I am trying to use cx_Oracle to query a table in oracle DB (version 11.2) and get rows with values in a column between a datetime range.

I have tried the following approaches:

  1. Tried between clause as described here, but cursor gets 0 rows

    parameters = (startDateTime, endDateTime)
    query = "select * from employee where joining_date between :1 and :2"
    cur = con.cursor()
    cur.execute(query, parameters)
    
  2. Tried the TO_DATE() function and Date'' qualifiers. Still no result for Between or >= operator. Noteworthy is that < operator works. I also got the same query and tried in a sql client, and the query returns results. Code:

    #returns no rows:
    query = "select * from employee where joining_date >= TO_DATE('" + startDateTime.strftime("%Y-%m-%d") + "','yyyy-mm-dd')"
    cur = con.cursor()
    cur.execute(query)
    #tried following just to ensure that some query runs fine, it returns results:
    query = query.replace(">=", "<")
    cur.execute(query)
    

Any pointers about why the between and >= operators are failing for me? (my second approach was in line with the answer in Oracle date comparison in where clause but still doesn't work for me)

I am using python 3.4.3 and used cx_Oracle 5.3 and 5.2 with oracle client 11g on windows 7 machine

Upvotes: 2

Views: 2650

Answers (2)

miracle173
miracle173

Reputation: 1983

Assume that your employee table contains the field emp_id and the row with emp_id=1234567 should be retrieved by your query.

Make two copies of your a program that execute the following queries

query = "select to_char(:1,'YYYY-MM-DD HH24:MI:SS')||' >= '||to_char(joining_date,'YYYY-MM-DD HH24:MI:SS')||' >= '||to_char(:2,'YYYY-MM-DD HH24:MI:SS') resultstring from employee where emp_id=1234567"

and

query="select to_char(joining_date,'YYYY-MM-DD HH24:MI:SS')||' >= '||to_char(TO_DATE('" + startDateTime.strftime("%Y-%m-%d") + "','yyyy-mm-dd'),'YYYY-MM-DD HH24:MI:SS') resultstring from employee where emp_id=1234567"

Show us the code and the value of the column resultstring

Upvotes: 2

holdenweb
holdenweb

Reputation: 37113

You are constructing SQL queries as strings when you should be using parameterized queries. You can't use parameterization to substitute the comparison operators, but you should use it for the dates.

Also, note that the referenced answer uses the PostgreSQL parameterisation format, whereas Oracle requires you to use the ":name" format.

Upvotes: 0

Related Questions