使用python程序将mysql表中的两个值插入另一个表中

时间:2009-01-01 22:54:43

标签: python mysql database

我正在编写一个Python程序(下面)的小问题。

我想从MySQL表中将两个值插入到Python程序的另一个表中。

这两个字段是优先级和产品,我从商店表中选择它们,我想将它们插入到产品表中。

有人可以帮忙吗?非常感谢。马克。

import MySQLdb

def checkOut():
    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 are taking out of the fridge: \n')
    cursor.execute('update shops set instock=0, howmanytoorder = howmanytoorder + 1  where barcode = %s', (user_input))
    db.commit()
    cursor.execute('select product, priority from shop where barcode = %s', (user_input))
    rows = cursor.fetchall()
    cursor.execute('insert into products(product, barcode, priority) values (%s, %s)', (rows["product"], user_input, rows["priority"]))
    db.commit()
    print 'the following product has been removed from the fridge and needs to be ordered'

2 个答案:

答案 0 :(得分:1)

嗯,同样的事情:

import MySQLdb

def checkOut():
    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 are taking out of the fridge: \n')
    cursor.execute('update shops set instock=0, howmanytoorder = howmanytoorder + 1  where barcode = %s', (user_input))
    db.commit()
    cursor.execute('select product, priority from shop where barcode = %s', (user_input))
    rows = cursor.fetchall()
  1. 你需要fetchall()??条码是我独一无二的,我想一个条码就是一个产品。所以,fetchone()就够了......不是吗??

  2. 在任何情况下,如果你做一个fetchall(),它的结果集不是一个结果。 所以rows["product"]无效。 它必须是

    for row in rows:
        cursor.execute('insert into products(product, barcode, priority) values (%s, %s, %s)', (row["product"], user_input, row["priority"]))
    db.commit()
    print 'the following product has been removed from the fridge and needs to be ordered'
    
  3. 或更好

    import MySQLdb
    
    def checkOut():
        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 are taking out of the fridge: \n')
        cursor.execute('update shops set instock=0, howmanytoorder = howmanytoorder + 1  where barcode = %s', (user_input))
        cursor.execute('insert into products(product, barcode, priority) select product, barcode, priority from shop where barcode = %s', (user_input))
        db.commit()
    

    修改:此外,您使用db.commit()几乎就像print - 在任何地方,您需要阅读并理解数据库的atomicity原则

答案 1 :(得分:1)

您没有提到问题所在,但在代码中您显示了这个问题:

cursor.execute('insert into products(product, barcode, priority) values (%s, %s)', (rows["product"], user_input, rows["priority"]))

你的values子句只有两个%s,它应该有三个:

cursor.execute('insert into products(product, barcode, priority) values (%s, %s, %s)', (rows["product"], user_input, rows["priority"]))