-1

現在、MySQL データベースと対話するプログラムを作成していて、問題が発生しています。ご覧のとおり、ユーザーが入力したバーコードに対応する製品を製品テーブルで検索するクエリを作成しました。

ユーザーが入力したバーコードが製品テーブルで見つかった場合、バーコード入力に対応する製品が在庫の製品と同じである在庫テーブルの「金額」フィールドを 1 増やしたいテーブル。

ご覧のとおり、変数を for ループに割り当てて、そのように機能させようとしましたが、機能していません。誰かがそれを行う方法について何か考えがありますか?

import MySQLdb

def look_up_product():
    db = MySQLdb.connect(host='localhost', user = 'root', passwd='$$', db='fillmyfridge')
    cursor = db.cursor (MySQLdb.cursors.DictCursor)
    user_input=raw_input('please enter the product barcode that you wish to checkin to the fridge: \n')
    if cursor.execute("""select * from products where product = %s""", (user_input)):
        db.commit()
        result_set = cursor.fetchall ()
        #i want here to assign a variable to this for loop and the line below = for product in result_set: 
            print "%s" % (row["product"])
        cursor.execute('update stocks set amount = amount + 1 where product = %s', (#here i want the result of the for loop))
        db.commit()
    else:
        print 'no not in products table'

どうもありがとう。

4

5 に答える 5

1

答えは、「変数を for ループに代入する」という意味によって異なります。for ループは実行の流れを制御するためのツールであるため、この表現は混乱を招きます。通常、値を持つとは考えられません。しかし、私はあなたが言いたいことを知っていると思います。ループが実行されるたびに、それが実行されprint "%s" % (row["product"])ます。ループの実行中にこれが作成するすべての文字列を保存したいと思います。また、後者はループ全体で同じになるため、あなたが意図row[product]したものではないと推測します。row["product"]次に、これを行うことができます:

mylist = []
for product in result_set: 
    mylist.append("%s" % (row[product],))

文字列を表示しなくても % 操作が機能することに注意してください -- これは、C から来た人々にとって驚きです。 Python のリスト内包表記を使用して、このイベントをより簡潔にすることもできます。

mylist = ["%s" % (row[product],) for product in result_set]
于 2009-01-02T01:54:59.753 に答える
0

結果として単一の行を期待していますか? もしそうなら、これを試してください:

row = cursor.fetchone()
print row["product"]
cursor.execute('update stocks set amount = amount + 1 where product = %s', row["product"])
于 2008-12-29T23:19:56.870 に答える
0

製品テーブルから取得した値から行 ID を取得する方法がわかりません。select * fromイディオムを使用せずに、必要な列を明示的に指定することをお勧めします。

コードを読みやすくするために、ID 取得用のヘルパー関数を導入しました。

def getAnIdFromValue(someValueTuple):
    '''This function retrieves some table row identifier from a row tuple'''
    returns someValueTuple[0]

複数の行が予想される場合は、次の関数本体を試してみます。

db = MySQLdb.connect(...)
cursor = db.cursor()
ids = []
cursor.execute("""select * from products where product = %s""", (user_input))
for value in cursor.fetchall():
    #value is a tuple. len(value) == number of columns in products table
    ids.append(getAnIdFromValue(value))
if len(ids):
    cursor.executemany("update stocks set amount = amount + 1 where product =%s", tuple(ids))
    db.commit()
else:
    print 'no not in products table'
于 2008-12-29T23:20:06.633 に答える
0

for ループ内にあるように、「update stocks...」行をインデントする必要があると思います。

于 2008-12-29T23:22:49.157 に答える
0

よしよし。また、最初の行で欠落していたコンマを修正しましたcursor.execute

import MySQLdb

def look_up_product():
    db = MySQLdb.connect(host='localhost', user = 'root',
                         passwd='$$', db='fillmyfridge')
    cursor = db.cursor (MySQLdb.cursors.DictCursor)
    user_input=raw_input('please enter the product barcode '
                         'that you wish to checkin to the fridge: \n')
    cursor.execute("""select * from products where product = %s""",
                   (user_input,))
    for row in iter(cursor.fetchone, None):
        print row["product"]
        cursor.execute('update stocks set amount = amount + 1' 
                       ' where product = %s', (row["product"],))
    db.commit()

もちろん、代わりにsqlalchemyをいつでも使用できます。

import sqlalchemy as sa
import sqlalchemy.orm

# Prepare high-level objects:
class Product(object): pass
engine = sa.create_engine('mysql://root:$$@localhost/fillmyfridge')
session = sa.orm.create_session(bind=engine)
product_table = sa.Table('products', sa.MetaData(), autoload=True)
sqlalchemy.orm.mapper(Product, product_table)

def look_up_product():
    user_input=raw_input('please enter the product barcode '
                         'that you wish to checkin to the fridge: \n')
    for prod in session.query(Product).filter(Product.product == user_input):
        print prod.product
        # Here's the nicety: to update just change the object directly:
        prod.ammount = prod.ammount + 1
    session.flush()
    session.commit()
于 2008-12-30T15:37:15.990 に答える