How do I update a MySQL table using executemany in Python

I am trying to update multiple items into a MySQL table in Python using executemany. I am not sure where I am going wrong.

Here’s the function:

def update_bid_items(itemlines):
    c = create_connection()
    db = c[1]
    cur = db.cursor() 
    sql = """UPDATE bid_items            
             SET item_id = %s,
             description = %s,
             quantity = %s,
             base_price = %s,
             tier_price = %s,
             amount = %s
             WHERE bid_head_id = %s AND 
             row_num = %s
          """
    vals = (itemlines,)
    cur.executemany(sql, vals)        
    db.commit()
    db.close()

Here is the data that I am passing into the function:

[(4, '110V wall plug', '1', '5.00', '5.00', '5.00', '16', 0), (2, 'carpet nails box of 100', '1', '19.95', '19.95', '19.95', '16', 2)]

I am getting the following error:

_mysql_connector.MySQLInterfaceError: Python type tuple cannot be converted

I also tried it with a list instead of tuples with this error:

_mysql_connector.MySQLInterfaceError: Python type list cannot be converted

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

itemlines is already a list of tuples, you don’t need to put it inside another tuple.

So get rid of vals and use

cursor.executemany(sql, itemlines)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x