python - 返回 100 个特定姓氏的记录

标签 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中包含的姓氏的所有记录。

最佳答案

Question: return all the records for the surnames contained in a tuple

核心是,创建一个具有与序列中一样多的绑定(bind) - ? 的查询。
需要 [:-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/

相关文章:

Android listview 滚动到底部以从 sqlite 加载更多数据

python - 如何在 SciPy 中获得正确的插值?

python - Pandas - 制作列 dtype 对象或因子

python - Dask ProgressBar 不适用于分布式后端

c - 无法打开数据库(在swift中使用c的sqlite)

list - 在多行 SQLite 表中查找重复项

sqlite - 日期参数在Delphi SQLite查询中误读

sql - 在Mac OS X 10.9中使用sqlite3

python - 计算 SVM 损失函数的梯度

python - celery python对象方法