вставить два значения из таблицы MySQL в другую таблицу с помощью программы Python - PullRequest
0 голосов
/ 02 января 2009

У меня небольшая проблема с программой на 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 ]

1 голос
/ 02 января 2009

Вы не упоминаете, в чем проблема, но в коде вы показываете это:

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

где в предложении значений есть только два% s, где должно быть три:

cursor.execute('insert into products(product, barcode, priority) values (%s, %s, %s)', (rows["product"], user_input, rows["priority"]))
1 голос
/ 02 января 2009

Ну, опять то же самое:

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'
    

или лучше

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 - где угодно, вам нужно прочитать и понять принцип атомарности для баз данных

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...