how to use parameters, including integer, float and string, when using sql in python?

Viewed 1190

I am trying to use SQL in Python to extract data.

It works fine when it is a simple query like:

query="""
      SELECT OBJECTID
      FROM ACTIVITY
      """
a=cursor.execute(query)

But when I try to put a number in it, then it will have an error:

enter image description here

And the same error also happen when i try LIMIT, ROWNUM etc. It looks like I cannot just put a number in the code like this.

I also tried this way:

enter image description here

But the same error occured.

Also, I tried:

query="""
      SELECT TOP %s OBJECTID
      FROM ACTIVITY
      """
num = 5
a=cursor.execute(query, num)

But I have got this:

enter image description here

So, i want to know how to transfer integers, floats and strings into sql in Python like parameters?

2 Answers

If its the number that is causing the issue, try to use the query this way:

query="""
      SELECT TOP %s OBJECTID
      FROM ACTIVITY
      """
num = (5)
a=cursor.execute(query, num)

Another way:

query="""
          SELECT TOP %(limit)s OBJECTID
          FROM ACTIVITY
          """
param = {
    'limit': 5
}
a=cursor.execute(query, param)

Not 100% sure, but this might fix the issue.

i think i figure it out. here is the example:

query="""
      SELECT OBJECTID,PROJECTOBJECTID
      FROM ACTIVITY
      where ROWNUM<=:num
      """
param={'num':5}
myRow=cursor.execute(query,param)
Related