简体   繁体   中英

[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 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:

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. In your approach, you are sending back every name in the table, and then checking those names in 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.

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. The result is a list of tuples where tuple elements are column values and list elements are different rows

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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