pythonmysqlsqldatabaseon-duplicate-key

How do i increment a value of column with condition?


my table looks something like this

id effect1(int) effect2(int) effect3(int) 
1     0           1               5
2     1           0               0

i have a function, which return 1to3 int value representing effect1,effect2,effect3 and "id"

i am trying to increment value of each effect by 1 when my function's returning "id" matches the "id" from my dataset otherwise creates new row and increase value of effect

for example

if my function returns (1,3) my table will become

id effect1(int) effect2(int) effect3(int) 
1     0           1               6
2     1           0               0

if my function returns (3,3) my table will become

id effect1(int) effect2(int) effect3(int) 
1     0           1               6
2     1           0               0
3     0           0               1

i have tried the following code using python, but failed. can someone please help me out here

i = (1,3) # the returning value from my function
if i[1] == 1:
    sql = "update test set effect1=effect1+1 WHERE id= ({})".format((str(i[0])))
    db.execute_query(myDb, sql)
elif i[1] == 2:
    sql = "update test set effect2=effect2+1 WHERE id= ({})".format((str(i[0])))
    val = (i[0],)
    db.execute_query(myDb, sql )
elif i[1] == 3:
    sql = "update test set effect3=effect3+1 WHERE id= ({})".format((str(i[0])))
    val = (i[0],)
    db.execute_query(myDb, sql )


def execute_query(connection, query):
    cursor = connection.cursor()
    try:
        cursor.execute(query)
        connection.commit()
        print("Query successful")
    except Exception as err:
        print(f"Error: '{err}'")

Solution

  • In your implementation, you did not check if the id already exists or not.

    I updated your code with an SQL statement that performs insertion/update as you mentioned-

    I also replaced the variable i (a list of two elements), with two variables named id and effect_no to improve the readability of the code. The if else statements are also not needed as the effect_no can be used/incorporated into the sql statement itself.

    Following is the updated code:

    id, effect_no = (1,3) # the returning value from your function
    sql = f"""INSERT INTO test (id, effect1, effect2, effect3)
    VALUES ({id}, 0, 0, 0)
    ON DUPLICATE KEY UPDATE effect{effect_no} = effect{effect_no} + 1"""
    db.execute_query(myDb, sql)
    
    def execute_query(connection, query):
        cursor = connection.cursor()
        try:
            cursor.execute(query)
            connection.commit()
            print("Query successful")
        except Exception as err:
            print(f"Error: '{err}'")
    

    Also, I found the INSERT ... ON DUPLICATE KEY UPDATE SQL statement here https://chartio.com/resources/tutorials/how-to-insert-if-row-does-not-exist-upsert-in-mysql/#using-insert--on-duplicate-key-update