I have the cursor with the query statement as follows:
cursor.execute("select rowid from components where name = ?", (name,))
I want to check for the existence of the components: name and return to a python variable. How do I do that?
I have the cursor with the query statement as follows:
cursor.execute("select rowid from components where name = ?", (name,))
I want to check for the existence of the components: name and return to a python variable. How do I do that?
To make it even shorter...:
Since the
name
s are unique, I really favor your (the OP's) method of usingfetchone
or Alex Martelli's method of usingSELECT count(*)
over my initial suggestion of usingfetchall
.fetchall
wraps the results (typically multiple rows of data) in a list. Since thename
s are unique,fetchall
returns either a list with just one tuple in the list (e.g.[(rowid,),]
or an empty list[]
. If you desire to know therowid
, then usingfetchall
requires you to burrow through the list and tuple to get to therowid
.Using
fetchone
is better in this case since you get just one row,(rowid,)
orNone
. To get at therowid
(provided there is one) you just have to pick off the first element of the tuple.If you don't care about the particular
rowid
and you just want to know there is a hit, then you could use Alex Martelli's suggestion,SELECT count(*)
, which would return either(1,)
or(0,)
.Here is some example code:
First some boiler-plate code to setup a toy sqlite table:
Using
fetchall
:yields:
Using
fetchone
:yields:
Using
SELECT count(*)
:yields:
As both existing answers (your own and @unutbu's) point out, the trick is that you do need to do some sort of fetching, after executing the
SELECT
, to check whether there have been any results to the select or not (whether you do it with a single fetch and check for none, or a fetch-all and check for an empty list, is a marginal difference -- given that you mention aUNIQUE
constraint they're basically equivalent approaches).For a very direct answer, you could
select count(*) from components where name = ?
, rather than selectingrowid
, if all you care is whether the given value for name is present or not (as opposed to, caring about what row id it's on, if at all;-). Executing this select, and fetching the result, gives you0
if the value is absent,1
if it's present (no other result is possible given what you mentioned in a comment about theUNIQUE
constraint on columnname
;-).I have found the answer.