返回100个特定姓氏的记录

发布于 2021-01-29 15:02:09

我有一个元组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
被浏览
70
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    问题 :返回所有记录中包含的姓氏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测试



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看