У меня небольшая проблема с программой 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'
Пожалуйста, напишите актуальный вопрос в виде предложения с заглавными буквами и вопросительного знака. Не могли бы вы переписать свое сообщение, включив в него актуальный вопрос?






Ну, опять то же самое:
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()
Вам нужен fetchall () ?? Я полагаю, что штрих-коды уникальны, и я полагаю, что один штрих-код относится к одному продукту. Итак, fetchone () достаточно .... не так ли ??
В любом случае, если вы выполняете функцию 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 - где угодно, вам нужно прочитать и понять принцип атомарность для баз данных.
Вы не упоминаете, в чем проблема, но в коде вы это показываете:
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"]))
@Ned: есть ли в rows скрипт? Разве это не набор результатов после fetchall (), мне кажется, ему нужны индексы. м Думаю в неправильном направлении?
впрочем, никаких проблем с этой опечаткой. Даже я этого не заметил.
А в чем именно проблема?