2013-04-28 46 views
0

我正在使用Python來使用MySQLdb訪問MySQL數據庫。我想從一個特定的表中的所有行「全局」如果WHERE可能/不可以爲空的SELECT語句的MySQL查詢

表全球有以下欄目:

regno 
make 
state 

用戶可以輸入REGNO,製造和狀態值僅獲取特定的行中,如果他不進入,那麼所有的行應是輸出

我試過下面的代碼:

import MySQLdb as db 
from config.py import * 

con = db.connect(server, user, pwd, database) 
cur = con.cursor() 

while(1): 
    print "-------Central Database-------" 
    print "Select : " 
    print "1. Balance Sheet\n2. Central Sheet" 

    choice = raw_input() 

    if choice == '3': 
     break 

    elif choice == '2': 

     regno = raw_input('Input Registration number (Blank for all) : ') 
     state = raw_input('Input state in/out (Blank for all) : ') 
     make = raw_input('Input make of the vehicle (Blank for all) : ') 

     if regno == '' and state == '' and make == '': 
      cur.execute("select * from global") 

     elif regno != '' and state != '' and make != '': 
      cur.execute("select * from global where regno=%s and state=%s and make=%s",(regno, state, make)) 
     ... 

正如你可以看到這會導致大量的所有if-elif的stateme NTS,有沒有什麼辦法的,我可以直截了當地使用MySQL查詢,如

select * from global where regno='' OR regno=%s 

回答

1

您只需添加所有單獨的條件從句到一個列表,然後聯合起來的條件清單;像這樣:

regno = raw_input('Input Registration number (Blank for all) : ') 
state = raw_input('Input state in/out (Blank for all) : ') 
make = raw_input('Input make of the vehicle (Blank for all) : ') 

conditions = [] 
args = [] 

if regno: 
    conditions.append("regno=%s") 
    args.append(regno) 

if state: 
    conditions.append("state=%s") 
    args.append(make) 

if make: 
    conditions.append("make=%s") 
    args.append(make) 

if conditions: 
    cur.execute("select * from global where " + " and ".join(conditions), args) 
else 
    cur.execute("select * from global") 

join功能通過將列表中的元素,例如之間的隔板串生成一個串出的列表的" and ".join(["foo", "bar"]變成foo and bar

相關問題