我有一个具有100个姓氏的元组l。我如何在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]来排除最后一个逗号...?,


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/

10-12 23:27