skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    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)
    

  2. What about using a SELECT statement in order to search the user’s access key?

    If it does not exist, run the INSERT statement:

    INSERT INTO Tokens (AccessToken, RefreshToken, UserID) VALUES (%s, %s, %s)
    

    If it doesn’t, run the UPDATE statement:

    UPDATE Tokens SET AcessToken=%s, RefreshToken=%s WHERE UserId=%s
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search