Brad
Brad

Reputation: 129

How to pass form data into multiple sqlite3 rows

I'm trying to pass form data in Flask into multiple rows of a sqlite database.

The form requires the user to enter multiple ingredients and ingredient amounts required, and I'm trying to pass these into individual rows, using the recipe name to group the rows together.

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()

Error

ValueError: parameters are of unsupported type

On the front-end, the data is being passed OK as I can see it within the network console.

Where is this code going wrong?

Thanks.

Upvotes: 1

Views: 359

Answers (1)

Timur
Timur

Reputation: 46

You should pass to Cursor.executemany a sequence of parameters (e.g a list of tuples, see documentation). Given error in your case means rname is not iterable (I am assuming it is a string).

You need to properly pack your data for executemany like so

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)

Upvotes: 1

Related Questions