0

我正在使用 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
4

1 回答 1

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"]become foo and bar

于 2013-04-28T10:18:37.450 回答