python - 我如何从 sqlite3_table WHERE column_name IN 变量元组中进行选择?

标签 python mysql sqlite select where-clause

我有这个元组:

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

这个topics元组会随着每个用户的变化而变化(他的长度也会变化)

如何从 sqlite3 表中仅选择 topic 列的值等于主题元组值之一的行?

我尝试使用此命令,但没有成功:

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

如果topics元组的长度每次都变化并且不是恒定的,我可以从这样的表中进行选择吗?

如果您能帮助我,我将非常感激:) 预先感谢!

最佳答案

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

类似于:

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)

关于python - 我如何从 sqlite3_table WHERE column_name IN 变量元组中进行选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61110792/

相关文章:

python - 使用 pandas 数据帧不等式保持 NaN

python - 值错误: Duplicate plugins for name projector

mysql - 如何停止对忽略的插入进行自动递增,这些插入不会对 MySQL 进行任何更改?

c# - C# 中的 MySQLConversionException 问题

Python 和 sqlite3.ProgrammingError : Recursive use of cursors not allowed

ios - 在 sqlite 中设置 user_version

python - Pandas read_csv : Columns are being imported as rows

python - Py_DECREF 和 PY_INCREF 的目的是什么?

mysql - 如何在 laravel.. 中实现 Select 查询?

android - 使用 ActionBarSherlock 和 SQLite CursorLoader 在 ListView fragment 中调用 restartLoader 的位置