Search code examples
pythonpython-2.7pymysql

pymysql update not working


I need to do an Update so I made this, but I got a problem with this code.

def runUpdate(query, aux):

#Establecemos la conexion con la base de datos
connection = pymysql.connect(host='localhost', user='root', password='root', db='influencers', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
try:
    with connection.cursor() as cursor:
        #Ejecutar query
        cursor.execute(query, aux)
        result = cursor.fetchall()
        #Guardar cambios conexion
        connection.commit()
finally:
    connection.close()

It seems ok, but when I made this:

runUpdate("""UPDATE Influencers SET tweets = '%s' WHERE usuario = '%s'""", (numTweets, user))

It throws me an error here:

cursor.execute(query, aux)

This is some of the console text: (...) return escape_str(value, mapping) File "/Library/Python/2.7/site-packages/pymysql/converters.py", line 71, in escape_str return "'%s'" % escape_string(value, mapping) File "/Library/Python/2.7/site-packages/pymysql/converters.py", line 68, in escape_string lambda match: ESCAPE_MAP.get(match.group(0)), value),)) TypeError: expected string or buffer

I think my syntax is wrong, but I don't see why. I'm learning to code at Python, so please be good :)


Solution

  • Please print your numTweets and user , check them is string or not.

    If your para numTweets and user is a list type, you should use

    cursor.executemany(operation, seq_of_params)
    

    check the document https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-executemany.html