简体   繁体   English

[Python] [sqlite3] if语句以查看值是否在数据库中?

[英][Python][sqlite3] If statement to see if value is in database?

Working on a project where I need to see if names are in a database. 在需要查看名称是否在数据库中的项目上。

I wanted to know if I could do an if statement something similar to: 我想知道是否可以执行类似于以下内容的if语句:

if name in c.execute("SELECT name FROM table"):
    print "Name is in table"
else:
    print "Name not in table"

Is this possible? 这可能吗?
More code is available upon request! 可根据要求提供更多代码!

I think you should use EXISTS here to determine if a matching record exists: 我认为您应该在这里使用EXISTS来确定是否存在匹配的记录:

c.execute("SELECT EXISTS(SELECT 1 FROM table WHERE name=? LIMIT 1)", (name,))
record = c.fetchone()
if record[0] == 1:
    print "Name is in the table"
else:
    print "Name not in table"

This approach has the benefit of allowing the SQLite database to do the heavy lifting of determining whether our name matches any record. 这种方法的好处是允许SQLite数据库进行繁重的工作来确定我们的名称是否与任何记录匹配。 In your approach, you are sending back every name in the table, and then checking those names in Python. 在您的方法中,您将发回表中的每个名称,然后在Python中检查这些名称。 This isn't optimal, because it wastes bandwidth and also FLOPs in your Python code which could have been better spent doing other things. 这不是最佳选择,因为这会浪费带宽,还会浪费Python代码中的FLOP,而这些本来可以更好地用于其他事情的。

You may try this - 您可以尝试-

c.execute("SELECT name FROM table")
rows = c.fetchall()

if (name,) in rows:
    print "Name is in table"
else:
    print "Name not in table"

After execute you have to fetch the result. execute您必须获取结果。 The result is a list of tuples where tuple elements are column values and list elements are different rows 结果是一个元组列表,其中元组元素是列值,而列表元素是不同的行

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

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