mysql 在python程序中为变量赋值'for循环'[已关闭]

but5z9lq  于 2023-03-11  发布在  Mysql
关注(0)|答案(5)|浏览(125)

**已关闭。**此问题需要debugging details。当前不接受答案。

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
七年前就关门了。
Improve this question
我正在写一个与MySQL数据库交互的程序,遇到了一个问题,正如你所看到的,我写了一个查询,在products表中查找与用户输入的条形码相对应的产品。
如果用户输入的条形码在products表中找到,我想将stocks表中的“amount”字段增加1,其中与条形码输入对应的产品与stocks表中的产品相同。
正如你所看到的,我试着给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'

万分感谢。

1cosmwyk

1cosmwyk1#

您是否希望结果为单行?如果是,请尝试以下操作:

row = cursor.fetchone()
print row["product"]
cursor.execute('update stocks set amount = amount + 1 where product = %s', row["product"])
56lgkhnf

56lgkhnf2#

我不确定如何从 products 表中获取行ID,我建议明确指定所需的列,不要使用select * from习惯用法。
我引入了用于id检索的helper函数,以使代码更易读:

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'
ct3nt3jp

ct3nt3jp3#

我认为您需要缩进“update stocks...”行,以便它位于for循环中。

iq0todco

iq0todco4#

好了,我还修正了你在第一行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()
wfveoks0

wfveoks05#

答案取决于你所说的“给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]

相关问题