python - 如何将表单数据传递到多个sqlite3行

标签 python sqlite flask

我正在尝试将 Flask 中的表单数据传递到 sqlite 数据库的多行中。

该表单要求用户输入所需的多种成分和成分数量,我尝试将它们传递到单独的行中,使用配方名称将行分组在一起。

if request.method == "POST":

    rname = request.form.get('rname')
    customer_id = request.form.get('customer_id')
    ingredient_id = request.form.getlist('product_code')
    ingredient_amount = request.form.getlist('ingredient_amount')

    con = sqlite.connect('database.db')
    cur = con.cursor()
    sql = """INSERT INTO recipes (rname, customer_id, ingredient_id, ingredient_amount) VALUES (?, ?, ?, ?)"""
    cur.executemany(sql, (rname, customer_id, ingredient_id, ingredient_amount,))
    cur.commit()

错误

ValueError: parameters are of unsupported type

在前端,数据传递正常,我可以在网络控制台中看到它。

这段代码哪里出错了?

谢谢。

最佳答案

您应该向 Cursor.executemany 传递一系列参数(例如元组列表,请参阅 documentation )。在您的情况下给出的错误意味着 rname 不可迭代(我假设它是一个字符串)。

您需要像这样正确打包executemany的数据

query_args = []

for ind, ingredient in enumerate(ingredient_id):
    data = (rname, customer_id, ingredient, ingredient_amount[ind])
    query_args.append(data)

cur.executemany(sql, query_args)

关于python - 如何将表单数据传递到多个sqlite3行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58403092/

相关文章:

python - matplotlib imshow -- 使用任何向量作为轴

sql - SQL 中的多重计数查询返回什么?

python - 返回 Basequery 对象,而不是从 sqlalchemy query.filter 中返回模型对象

java - 在java webapp中使用现有的sqlite数据库

javascript - Flask 和 Angular Web 应用程序路由

python - 以最聪明的 pythonic 方式将用户返回到 flask 中的引荐来源网址

给定元音变音字符时,python os.popen 失败

python - 如何在运行tensorflow时使用命令行传递数字列表?

python - 我这个时间复杂度计算哪里出错了?

sql - 从至少具有该状态的一组重复记录中选择具有给定状态的一条记录