how can i SELECT FROM sqlite3_table WHERE column_name IN variable tuple?

Viewed 74

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 Answers

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