Snowman288
Snowman288

Reputation: 107

How to use multiple where varibles in my sql select statement in python?

Question I have a simple application to query some of my oracle tables I want to be able to grab the value of my text boxes which work but, I keep getting this error any help would be greatly appreciated!

test.py

def grabEnts():
   global date 
   connection = cx_Oracle.connect('xxxxxxxx/[email protected]:xxxx/xxx')
   cursor = connection.cursor()
   startdate = e1.get()
   enddate = e2.get()
   #fs = datetime.date(startdate)
   #fe = datetime.date(endate)
   //this works but, I would like to use both startdate and endate
   #cursor.execute("SELECT EMP_ID FROM TO_ENTRIES WHERE LEAVE_START >= '%s'" % startdate)
    //Like this but I can't get it to work I keep getting this error 
    File "test.py", line 62, in grabEnts
   cursor.execute('SELECT EMP_FIRST_NAME FROM TO_ENTRIES WHERE LEAVE_START >=%s AND LEAVE_END <=%s', startdate, enddate)
   TypeError: function takes at most 2 arguments (3 given)

   cursor.execute('SELECT EMP_FIRST_NAME FROM TO_ENTRIES WHERE LEAVE_START >=%s AND LEAVE_END <=%s', startdate, enddate)
   for row in cursor:
       outputent.writerow(row)
   cursor.close()
   connection.close()

Upvotes: 0

Views: 117

Answers (2)

Ward
Ward

Reputation: 2852

Using string formatting to generate SQL is general a bad idea. If a user inputs something like ; DROP TABLE blah this will be executed in your code. This is a typical example of SQL injection...

To avoid, use parameters in your query, like so:

cursor.execute('SELECT EMP_FIRST_NAME FROM TO_ENTRIES WHERE LEAVE_START between :start AND :end', {'start': 1, 'end': 10})

Upvotes: 0

Tom Karzes
Tom Karzes

Reputation: 24052

When providing multiple values for a format string, you need to wrap them in parentheses:

"My name is %s.  Your name is %s." % ("Sam", "Joe")

Upvotes: 1

Related Questions