小编典典

返回100个特定姓氏的记录

python

我有一个元组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


阅读 172

收藏
2021-01-20

共1个答案

小编典典

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

2021-01-20