我正在使用 Python 使用 MySQLdb 访问 MySQL 数据库。我想从特定表“全局”中获取所有行
表 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