如何解决mysql更新当前数据
我想根据isUpVote布尔值将upVote列值增加/减少1。我在尝试以下代码时收到此错误。 postID和upVote值都是整数。
MySQLdb._exceptions.ProgrammingError:(1064,“您的SQL语法有误;请查看与您的MySQL服务器版本相对应的手册,以在'upVote'附近使用正确的语法:0}'-在1处postID ='2'在第1行“)
@app.route('/posts/upvote',methods=['GET','PATCH'])
def upvote_post():
if request.method == 'PATCH':
data = request.get_json()
print(data)
postID = data['postID']
isUpVote = data['isUpVote']
cur = mysql.connection.cursor()
cur.execute("SELECT upVote FROM posts WHERE postID = '{}'".format(postID))
current_upVote = cur.fetchone()
if isUpVote:
cur.execute("UPDATE posts SET upVote = '{0}' + 1 WHERE postID = '{1}'".format(current_upVote,postID))
else:
cur.execute("UPDATE posts SET upVote = '{0}' - 1 WHERE postID = '{1}'".format(current_upVote,postID))
我该如何解决错误? 而且我想知道是否有一种更简单的方法可以在不定义current_upVote变量的情况下一行更新upVote值。
解决方法
您根本不需要选择查询,您可以简单地将当前值加或减1。
@app.route('/posts/upvote',methods=['GET','PATCH'])
def upvote_post():
if request.method == 'PATCH':
data = request.get_json()
print(data)
postID = data['postID']
isUpVote = data['isUpVote']
cur = mysql.connection.cursor()
if isUpVote:
cur.execute("UPDATE posts SET upVote = upVote + 1 WHERE postID = '{0}'".format( postID))
else:
cur.execute("UPDATE posts SET upVote = upVote - 1 WHERE postID = '{0}'".format( postID))
,
current_upvote
是包含您获取的行的字典。您需要从中提取值。
您还可以使用Python进行算术运算,然后只需执行一个查询即可更新。
您应该使用参数而不是字符串格式来替代查询。
cur.execute("SELECT upVote FROM posts WHERE postID = %s",(postID,))
current_upVote = cur.fetchone()
if isUpvote:
vote = current_upVote['upVote'] + 1
else:
vote = current_upVote['upVote'] - 1
cur.execute("UPDATE posts SET upVote = %s WHERE postID = %s",(vote,postID))
但是,最好的方法是nbk的答案。我只发布了此信息以解释您的代码为什么不起作用,并说明了参数的正确使用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。