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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Since the
names are unique, I really favor your (the OP’s) method of usingfetchoneor Alex Martelli’s method of usingSELECT count(*)over my initial suggestion of usingfetchall.fetchallwraps the results (typically multiple rows of data) in a list. Since thenames are unique,fetchallreturns either a list with just one tuple in the list (e.g.[(rowid,),]or an empty list[]. If you desire to know therowid, then usingfetchallrequires you to burrow through the list and tuple to get to therowid.Using
fetchoneis better in this case since you get just one row,(rowid,)orNone.To get at the
rowid(provided there is one) you just have to pick off the first element of the tuple.If you don’t care about the particular
rowidand 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: