2

I have this tuple:

topics = ('sport', 'math', 'science', 'literature')

This topics tuple changes for every user (his length also changes)

How can I select from a sqlite3 table only the rows where their topic column's value equals to one of the topics tuple's values?

I tried to use this command but it didn't work:

conn = sqlite3.connect('questions_stack.db')
c = conn.cursor()
c.execute("""SELECT * FROM questions WHERE topic IN ?""", subject_tuple)

Can I select from the table like that if the topics tuple's length changes every time and is not constant?

I'd really appreciate it if you could help me :) Thanks in advance!

1
  • both the values and the length of the tuple changes for each user Commented Apr 8, 2020 at 22:07

1 Answer 1

2

You need to count how many values there are in the list, and generate the corresponding placeholders.

Something like:

conn = sqlite3.connect('questions_stack.db')
c = conn.cursor()
binds = ",".join("?" * len(subject_tuple))
sql = '''select * from questions where topic in ({})'''.format(binds)
cur.execute(sql, subject_tuple)
Sign up to request clarification or add additional context in comments.

Comments

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.