我需要做一个更新,所以我做了这个,但是这个代码出了问题。
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()
似乎没问题,但是当我做到这一点时:
runUpdate("""UPDATE Influencers SET tweets = '%s' WHERE usuario = '%s'""", (numTweets, user))
它在这里引发了一个错误:
cursor.execute(query, aux)
这是一些控制台文本:
(...)
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
我认为我的语法错了,但我不明白为什么。我正在学习使用Python编写代码,所以请保持良好:)
答案 0 :(得分:1)
请打印您的numTweets和用户,检查它们是否为字符串。
如果para numTweets和user是列表类型,则应使用
cursor.executemany(operation, seq_of_params)
查看文档https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-executemany.html