mysql - 使用 python(flask) 更新 MySQL 中的最后一个条目
问题描述
我正在尝试创建一个函数来更新第一个名称,其中 id 是数据库中的最后一个。这需要是动态的,以便在生成新行时,它将更新包含最高 id 的名字的行。
我尝试了两种方法,一种SELECT * FROM names ORDER BY id DESC LIMIT 1
在下面的代码中使用,另一种使用SELECT MAX(id) FROM mytable
. 两种方法都失败并返回以下错误消息。
MySQLdb._exceptions.ProgrammingError: not all arguments converted during bytes formatting
这是包含错误的服务一中的功能:
@app.route("/edit_first_name", methods = ['GET','POST'])
def edit_first_name():
if request.method == 'POST':
"""
Collect first name from service 4.
Amend the first name of last entry in database and display entry in table.
"""
updated_first_name = requests.get("http://service_4:5003/first_name")
first_name = updated_first_name.text
cur = mysql.connection.cursor()
cur.execute('UPDATE names SET first_name = %s WHERE id = (SELECT * FROM names ORDER BY id DESC LIMIT 1)', (first_name))
cur.execute('SELECT * FROM names')
rows = cur.fetchall()
names = []
for row in rows:
names.append(row)
mysql.connection.commit()
cur.close()
return render_template("layout.html", first_name = first_name, title = "Name Generator", names = names)
这是生成名字的服务 4 的代码:
from flask import Flask, request
import random
app = Flask(__name__)
@app.route("/first_name", methods = ['GET'])
def first_name():
list = ["Valeria","Perla", "Elisabeth", "Joanna", "Jordan"]
list += ["Violet", "Conor", "Whitney", "Ethen", "Ronan", "Selina", "Simone"]
return list[random.randrange(12)]
if __name__ == "__main__":
app.run(port = 5001, host = "0.0.0.0", debug = True)
解决方案
您不能在从正在更新的同一个表中选择的更新中使用子选择。您需要在单独的查询中获取 ID,这将使您已经存在的并发问题(更新错误行的风险)变得更糟。
总体而言,您主要需要一种不同的基本方法来更好地定义您正在做的事情。
推荐阅读
- javascript - 挣扎着通过导航传递props,相信和我的AysncyStorage set multiple有关
- python-3.x - Vigenere Cipher:遇到问题
- python - Python maxplotlib - boxplot 子图 + 散点图
- javascript - 如何在javascripts中计算日间添加的多个输入onchange of value的值
- python - 使用特定字符串过滤数据框的列
- python-3.x - 如何在for循环中为字符串打印空格而不是下划线
- powerbi - DAX 测量。如何计算性能划分目标
- python - SQLAlchemy 一对(多的一些)关系
- javascript - 无法使用函数在数组中定位 JS 生成的按钮,出现“无法读取属性 'setAttribute' of null”错误
- apache-flink - Ververica 平台| Flink 所需的上下文属性不匹配