M.Yavuz YAĞIŞ
M.Yavuz YAĞIŞ

Reputation: 113

Passing Array into SQL query in Python

I am following the CS50 of Harvard and I don't want to use CS50 library that they use for lecture purposes, but I could not figure out how to make this code work. A little help would be greatly appreciated

import sqlite3
from flask import Flask, redirect, render_template, request, session
from flask_session import Session

# Configure app
app = Flask(__name__)

# Connect to database
db = sqlite3.connect("store.db",check_same_thread=False)

c = db.cursor()
# Configure sessions
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)


@app.route("/")
def index():
    books = db.execute("SELECT * FROM books")
    list =[dict(id=book[0], title=book[1]) for book in books.fetchall() ]
    return render_template("books.html", books=list)


@app.route("/cart", methods=["GET", "POST"])
def cart():

    # Ensure cart exists
    if "cart" not in session:
        session["cart"] = []

    # POST
    if request.method == "POST":
        id = request.form.get("id")
        if id:
            session["cart"].append(id)
        return redirect("/cart")

    # GET
   
    books = db.execute("SELECT * FROM books WHERE id IN (?)", [session("cart")])
    list =[dict(id=book[0], title=book[1]) for book in books.fetchall()]
    return render_template("cart.html", books=list)

The error is at the books=db.execute... line.

Error is :
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 9 supplied

I pressed the cart button 9 times, it is incrementing. Tried other solutions, could not still figure out.

Upvotes: 2

Views: 965

Answers (1)

balderman
balderman

Reputation: 23815

books = db.execute("SELECT * FROM books WHERE id IN (?)", [session("cart")])

should be

query = f"SELECT * FROM books WHERE id IN ({','.join(['?'] * len(session['cart']))})"
books =  db.execute(query,session['cart'])))

Upvotes: 1

Related Questions