我有一个元组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
中包含的姓氏的所有记录。
答案 0 :(得分:2)
问题:返回
中包含的所有姓氏记录tuple
核心是创建一个查询,该查询具有与序列中一样多的绑定-?
-
需要[:-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
进行了测试