Search code examples
mysqlpython-3.xdatabasesql-update

Query to update a table without duplicate in python3


I'm doing a project; I have to update a table with dynamic values from a script. My table schema, that could be wrong is:

Structure of my datasbase

Structure of the table I am working with

I am trying to insert the new values of AccessToken, RefreshToken, UserID and if there is already a UserID with the same ID just update that values. My code is this one:

try:
        with conexion.cursor() as cursor:

            query = "INSERT INTO Tokens (AccessToken, RefreshToken, UserID) ON DUPLICATE KEY UPDATE UserID = VALUES(UserID), VALUES (%s, %s, %s, %s)"
            val = (AccessToken, RefreshToken, User_ID, User_ID)

            cursor.execute(query, val)

        conexion.commit()

I don't use well the keys and maybe there's the error. The error I get in my console it's:

pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ON DUPLICATE KEY UPDATE UserID = VALUES(UserID), VALUES ('eyJhbGciOiJIUzI1NiJ9.e' at line 1")

That code in VALUES it is actually the AccessToken instead of the User_ID

Any idea what I'm doing wrong?


Solution

  • Finally, I solved it with this query:

    INSERT INTO Tokens (userID, accessToken, refreshToken) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE accessToken = %s, refreshToken = %s;"
                val = (User_ID, AccessToken, RefreshToken, AccessToken, RefreshToken)
    
                cursor.execute(query, val)