我有一个元组,l
,有 100 个姓氏。我怎样才能在 sqlite3 中做这样的事情:
l = ("Smith", "Murphy", "Owens", ...)
with sqlite3.connect("census.sqlite") as conn:
c = conn.cursor()
c.execute('select firstname, surname from census_data where surname in ?',(l,))
这样我就可以返回l
中包含的姓氏的所有记录。
最佳答案
Question: return all the records for the surnames contained in a
tuple
核心是,创建一个具有与序列中一样多的绑定(bind) - ?
的查询。
需要 [:-1]
来排除最后一个逗号 ...?,
。
SQL As Understood By SQLite - whereclause
surnames = ("Smith", "Murphy", "Owens") bindings = '?,'*len(surnames) QUERY = "select firstname, surname from census_data where surname in ({});" .format(bindings[:-1]) print(QUERY) # >>> select firstname, surname from census_data where surname in (?,?,?); cur.execute (QUERY, surnames)
使用 Python:3.5.3 - sqlite3:2.6.0 进行测试
关于python - 返回 100 个特定姓氏的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55382411/