-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

There there. I also fixed a comma you were missing on the first cursor.execute line.

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()

Of course, you could always use sqlalchemy instead:

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 回答
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 循环内。

于 2008-12-29T23:22:49.157 回答