繁体   English   中英

使用 python(flask) 更新 MySQL 中的最后一个条目

[英]Update last entry in MySQL using python(flask)

我正在尝试创建一个 function 来更新第一个名称,其中 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

这是服务一中的 function,其中包含错误:

@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,这将使您已经存在的并发问题(更新错误行的风险)变得更糟。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM