Question

I am trying to use cx_Oracle to execute an sql statement from Python. The SQL I have written seems to work in my Oracle database client (SQL Developer) but seems to pull back every record when executed from the Python script

#setup db connection here...
curs = db.cursor()

sql=("\
SELECT a.first, c.second, c.third, c.fourth FROM FIRST_DB.first_table a,\
FIRST_DB.second_table b,\
OTHER_DB.third_table c\
\
WHERE\
a.identifier='XXXX' and\
a.this_row = b.that_row and\
b.this_row = c.that_row;\
")

curs.execute(sql)
print curs.description
result=curs.fetchmany()
while result:
    for i,j,k,l in result:
        print i,j,k,l
    result=curs.fetchmany()
db.close()

This returns every record in the view and not just the one containing 'XXXX' as it does in the SQL developer...

Can anyone see either a problem in the SQL or in the way I am doing this?

Cheers in advance

Was it helpful?

Solution

Try to use triple-quoted strings. It is a good way to have readable multi-line strings. I don't have an Oracle DB to test here, but I am guessing the lack of white space is causing you problems.

Print your SQL statement and you will see how it actually looks with the backslashes removed:

sql=("\
SELECT a.first, c.second, c.third, c.fourth FROM FIRST_DB.first_table a,\
FIRST_DB.second_table b,\
OTHER_DB.third_table c\
\
WHERE\
a.identifier='XXXX' and\
a.this_row = b.that_row and\
b.this_row = c.that_row;\
")

>>> print sql

SELECT a.first, c.second, c.third, c.fourth FROM FIRST_DB.first_table a,FIRST_DB
.second_table b,OTHER_DB.third_table cWHEREa.identifier='XXXX' anda.this_row = b
.that_row andb.this_row = c.that_row;

OTHER TIPS

As far as I know, some tools like SQL*Plus have problems with blank lines inside a sql statement. Not sure how Python passes your statement to the DB, but maybe taking out that blank line before your where-clause will help:

#setup db connection here...
curs = db.cursor()

sql=("\
SELECT a.first, c.second, c.third, c.fourth FROM FIRST_DB.first_table a,\
FIRST_DB.second_table b,\
OTHER_DB.third_table c\
WHERE\
a.identifier='XXXX' and\
a.this_row = b.that_row and\
b.this_row = c.that_row;\
")

curs.execute(sql)
print curs.description
result=curs.fetchmany()
while result:
    for i,j,k,l in result:
        print i,j,k,l
    result=curs.fetchmany()
db.close()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top