【问题标题】:Check if a row exists in sqlite3?检查sqlite3中是否存在一行?
【发布时间】:2015-07-14 12:55:21
【问题描述】:

如何使用 Python 3 和 sqlite3 正确检查数据库表中是否存在行?

这是我的原始代码:

cursor.execute("SELECT name, age FROM people WHERE pin=?", (pin, ))
name, age = cursor.fetchone() or ('', 0)

所以目前我正在使用or ('', 0) 为它们设置默认值,我真的不喜欢这样。

有没有办法检查这个人是否已经存在?像这样的东西(伪):

if cursor.exists("pin IN people"):
    cursor.execute("SELECT name, age FROM people WHERE pin=?", (pin, ))
    name, age = cursor.fetchone()

【问题讨论】:

  • 如果没有,fetchone 不会引发异常吗?
  • 如果没有选择则返回 None

标签: python python-3.x sqlite


【解决方案1】:

不要打电话给fetchone();只需将光标视为迭代器:

for row in c.execute("SELECT name, age FROM ..."):
    name, age = row
    break
else:
    print("not found")

【讨论】:

  • 不知道你可以这样做,我现在在工作所以无法测试它,但如果它有效我会接受!
【解决方案2】:

这样的?

vals = cursor.execute("SELECT name, age FROM people WHERE pin=?", (pin, )).fetchone()

if vals:
    name, age = vals

【讨论】:

    【解决方案3】:

    您可以使用计数查询:

    if c.execute("SELECT count(*) FROM people WHERE pin=?", (pin, )).fetchone()[0] > 0:
        ...
    

    【讨论】:

      【解决方案4】:

      或者,如果您的表很大并且您将受益于pin 上的索引,您也可以使用EXISTS 来验证查询,看看这个SO,您可以这样做:

      c = cursor.execute("""SELECT EXISTS (SELECT 1 
                                           FROM people 
                                           WHERE pin=?
                                           LIMIT 1)""", (pin, )).fetchone()[0]
      if c:
          ...
      

      游标将返回(1,)(如果返回1 行或更多行)或(0,)(如果返回None),c 将是1/0,因为fetchone()[0] 将获得整数值1/0从上面。

      Exists 可能更高效,具体取决于表的大小以及是否在查询的字段上设置了索引。

      【讨论】:

        猜你喜欢
        • 2013-09-19
        • 2018-04-22
        • 1970-01-01
        • 1970-01-01
        • 2012-11-09
        • 2012-10-07
        • 1970-01-01
        • 2012-08-07
        • 2011-03-30
        相关资源
        最近更新 更多