0

MySQLdbを使用してMySQLデータベースにアクセスするためにPythonを使用しています。特定のテーブル「グローバル」からすべての行を取得したい

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

于 2013-04-28T10:18:37.450 に答える