0

I trying to use sqlite3 query like this one:

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

Where session["cart"] is a dynamic list. For example: session["cart"] = ['1', '7']

I get an error as given in title while trying to execute it.

How may I insert whole list in the question mark placeholder? I can't use multiple question marks, because their number may vary.

Does anyone has any clue? Or maybe better idea how to achieve so?

1 Answer 1

1

You will have to format your python list into something sql can read, this is easily done with str.join

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

in case you are unfamiliar, str.join(iterable) will make a string with all the string representations of the items in the iterable separated by the str you called join on, i.e. '---'.join([1,2,3]) will produce "1---2---3" (a string)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, works perfectly. I know this method, but I was completely fixed with idea that I may do so without additional variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.