【问题标题】:Update last entry in MySQL using python(flask)使用 python(flask) 更新 MySQL 中的最后一个条目
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多