我如何从sqlite3_table WHERE column_name中选择变量元组?

我有这个元组:

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?

我尝试使用此命令,但它不起作用:

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?

如果您能帮助我,我将不胜感激:) 提前致谢!

评论
  • 小喵喵YY
    小喵喵YY 回复

    您需要计算列表中有多少个值,并生成相应的占位符。

    就像是:

    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)