I am implementing a food ordering function using a Python flask.
I am having difficulty inserting into mysql db, so I ask a question.
First, I had to take data from a table called menu and insert it into order_detail, so I used insert into select.
I am trying to store each data in the order_detail table through a for statement, but I don't know how to put the variables of the for statement in mysql.
The code is below.
def cart_insert(element):
conn = pymysql.connect(**config)
cur = conn.cursor()
for item in element:
sql = "insert into order_detail (order_id, menu_name, food_qty, food_price)\
select 1, item , 1, menu_price from menu where menu.menu_name=item "
cur.execute(sql)
OH!!!!!! I SOLVED IT!!!!
My problem was how to put a python variable into a mysql db column.
If you're struggling, try this.
def cart_insert(element):
conn = pymysql.connect(**config)
cur = conn.cursor()
for item in element:
sql = "insert into order_detail (order_id, menu_name, food_qty, food_price)\
select 1, %s, 1, menu_price from menu where menu.menu_name=%s"
cur.execute(sql, (item, item))
I used an insert into select statement to fetch data from another table(menu table).
It was a problem to insert Python variables into the DB here. Since it is defined to be received in list format, you can use %s in pymysql when using python variables.
It is defined to receive in list form, so you can use %s in pymysql when using python variables.
Define the SQL and put the SQL you just created into the execution function. And if you want to put python variables in db, you just need to input python variables as many as %s.