简体   繁体   中英

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

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!

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM