我正在编写一个与MySQL数据库交互并且有问题的程序。正如您所看到的,我已经编写了一个查询,该查询将在products表中查找与用户输入的条形码对应的产品。
如果在产品表中找到了用户输入的条形码,我想在库存表中将'amount'字段增加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'
感谢百万。
答案 0 :(得分: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]
答案 1 :(得分:0)
您期待结果是一行吗?如果是这样,试试这个:
row = cursor.fetchone()
print row["product"]
cursor.execute('update stocks set amount = amount + 1 where product = %s', row["product"])
答案 2 :(得分:0)
我不确定如何从 products 表中获取的值获取行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'
答案 3 :(得分:0)
我认为你需要缩进“update stocks ...”行,以便它在for循环中。
答案 4 :(得分: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()