Search code examples
pythonoracle-databasecursorcx-oracleexecute

cx_oracle python and select Like %variable%


I'm trying to execute a query based on "tempo" variable,using %tempo% none of the solution that I found here help my problem

import cx_oracle
query="""SELECT description, local, point, date  
           FROM tbl_ext_tempo 
          WHERE point like '%' || :0 || '%' 
            AND ROWNUM < 8 
          ORDER BY date DESC
       """
cursor.execute(query, tempo)

Exception Value:

ORA-01036: illegal variable name/number

Solution

  • You can define a list(lst), and append the current string to it as formatted

    lst = []
    tempo = 'someValue'
    query="""
             SELECT description, local, point, "date"
               FROM tbl_ext_tempo
              WHERE point LIKE :0          
                AND ROWNUM < 8
              ORDER BY "date" DESC
           """   
    lst.append('%{}%'.format(tempo))
    cursor.execute(query,(lst))
    print(cursor.fetchall())
    

    date cannot be a column name as being a reserved keyword, perhaps it might be "date" as quoted.