如何在python中的sql select语句中使用多个where varible?

时间:2015-11-03 14:58:59

标签: python python-2.7

问题我有一个简单的应用程序来查询我的一些oracle表,我希望能够获取我的文本框的值,但是,我一直得到这个错误,任何帮助都会非常感激!

test.py

def grabEnts():
   global date 
   connection = cx_Oracle.connect('xxxxxxxx/xxxxxxxx@x.x.x.x: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()

2 个答案:

答案 0 :(得分:1)

为格式字符串提供多个值时,需要将它们括在括号中:

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

答案 1 :(得分:0)

使用字符串格式生成SQL通常是一个坏主意。如果用户输入类似; DROP TABLE blah的内容,则会在您的代码中执行。这是SQL注入的典型示例......

要避免,请在查询中使用参数,如下所示:

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