2

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Sorry, I had a typo in my question. My tuples actually do have 5 values. I have re-edited the question. Thanks for spotting it and sorry for misleading you.
But you have solved my problem!! I just removed the duplicate element from the 5-element tuple and made it a 4-element tuple, then applied your answer. It works!!
Again thanks for spotting the mistake. I have re-edited the question.
Glad it worked, although I'm not sure why it didn't work with the 5-tuples.
I was lucky as one of the elements is a duplicate. But what if there were no duplicates? How would the code look like? I think I will open another question on this issue.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.