I am using MySql and python MySQLdb module. I want to insert a new row or update certain fields if the row already exists.
The list of tuples that contains the values to be entered looks like this;
ListTuple=[('A_val', 'B_val', 'C_val', 'D_val', 'C_val'), ('AA_val', 'BB_val', 'CC_val', 'DD_val', 'CC_val')]
The MySQL query looks like this;
query="""INSERT INTO table (A, B, C, D)
VALUES (%s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
C= %s
"""
try:
Cursor.executemany(query, ListTuple)
Db_conn.commit()
except:
Db_conn.rollback()
Query execution fails with this code. Can someone point out what is wrong with it? Thank you very much for your help.
Try this:
query="""INSERT INTO table (A, B, C, D)
VALUES (%s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
C= VALUES(C)
"""
Your query had 5 placeholders, but your tuples only have 4 values. You needed to duplicate C
, but the VALUES(C)
option will automatically get that from the original VALUES clause.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.