返回100个特定姓氏的记录

时间:2019-03-27 16:41:56

标签: python sqlite

我有一个元组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中包含的姓氏的所有记录。

1 个答案:

答案 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

进行了测试
相关问题