【发布时间】:2020-07-09 15:17:01
【问题描述】:
我正在尝试创建一个函数来更新第一个名称,其中 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)
【问题讨论】:
-
排序以获得最大值效率不高。
-
另请注意,在多用户环境中,您最终可能会更新错误的行。
标签: mysql python-3.x flask