首页 > 解决方案 > 使用 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)

标签: mysqlpython-3.xflask

解决方案


您不能在从正在更新的同一个表中选择的更新中使用子选择。您需要在单独的查询中获取 ID,这将使您已经存在的并发问题(更新错误行的风险)变得更糟。

总体而言,您主要需要一种不同的基本方法来更好地定义您正在做的事情。


推荐阅读