返回100个特定姓氏的记录
我有一个元组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
。
-
问题 :返回所有记录中包含的姓氏
tuple
核心是创建一个查询,该查询具有与
?
序列中一样多的绑定。
在[:-1]
需要排除最后一个逗号...?,
。- SQLite理解的SQL-子句
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测试
- SQLite理解的SQL-子句