简体   繁体   English

检查sqlite3中是否存在行?

[英]Check if a row exists in sqlite3?

How do I properly check if a row exists in my database table using Python 3 and sqlite3? 如何使用Python 3和sqlite3正确检查数据库表中是否存在行?

Here's my original code: 这是我的原始代码:

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

So currently I'm setting them a default value with the or ('', 0) , and I really don't like this. 所以目前我用or ('', 0)设置默认值,我真的不喜欢这个。

Is there a way to check if the person already exists? 有没有办法检查这个人是否已经存在? Something like this (pseudo): 像这样的东西(伪):

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

Don't call fetchone() ; 不要调用fetchone() ; just treat the cursor as an iterator: 只需将游标视为迭代器:

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

Something like this? 像这样的东西?

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

if vals:
    name, age = vals

You could use a count query: 您可以使用计数查询:

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

Alternatively you may use EXISTS to validate the query if your table is large and you will benefit with index on pin , take a look at this SO , so you may do: 或者你可以使用EXISTS验证查询,如果你的表很大,你将受益于pin上的索引,看看这个SO ,所以你可以这样做:

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

The cursor will return either (1,) (if 1 or more rows returned) or (0,) (if None returned), c will be either 1/0 as fetchone()[0] will get the integer value 1/0 from above. 游标将返回(1,) (如果返回1行或更多行)或(0,) (如果返回None),则c将为1/0因为fetchone()[0]将获得整数值1/0从上面。

Exists could be more efficient depending on the size of your table and if you have index set on the field you query. 根据您的表的大小以及您在查询的字段上是否设置了索引, Exists可以更高效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM