我正在使用Python来使用MySQLdb访问MySQL数据库。我想从特定表中获取所有行“global”
表global包含以下列:
regno
make
state
用户可以输入regno,make和state值以仅获取特定行,如果他没有输入则所有行都应作为输出
我尝试过以下代码:
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语句,有什么方法我可以直接使用MySQL查询,例如
select * from global where regno='' OR regno=%s
答案 0 :(得分: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
。