Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top