comparing results of fetchall() with a known value

Steve Holden sholden at holdenweb.com
Tue Aug 28 10:39:23 EDT 2001


"Jeff" <jhardcastle at solarc.com> wrote in message
news:e33814e8.0108201528.57883ea1 at posting.google.com...
> Hi - I'm new to Python, and am having trouble reading the results of a
> database call using fetchall().  Here's my situation:
>
Welcome to Python. It's great for database work.

> I have a database table containing a list of names, and I have a
> string variable containing a name.  I need logic that will determine
> if my string exists in the database table.  So I have a simple sql
> like "select name from employees", and I have a string empname =
> 'Jones', and I need to verify that 'Jones' is in the employees list
> (assume duplicate names are not an issue in this case).
>
One way to do this (assuming C is a cursor open to your database of choice)
would be something like:

C.execute("SELECT count(*) FROM employess WHERE name=?", (empname, ))
result = c.fetchall()
if result[0] == (1, ):
    ... there's one employee...

You should certainly use SQL's power to do what it does best: query the
database!

> Here's what I've done: I created an odbc connect to the database,
> opened a cursor, executed the sql, then set a variable: namelist =
> cursor.fetchall().  What's got me stumped is that "namelist" is a list
> of tuples with sample data like: [('smith',), ('johnson',),
> ('jackson',), ('jones',)]
>
> If this were a normal tuple or list, I could easily use:
>
> "if empname in namelist:
>      ....execute code...."
>
> But with the list of tuples, I don't know how to easily do this. My
> hunch is that there must be some way to convert that list of tuples
> into a list of single values, since I only need the first element of
> the tuple like 'jackson' from ('jackson',).  Once I had the list of
> single values, my if statement above would work.
>
If you have such a list of tuples, an easy way to check for the presence oif
a single name is to construct the tuple you are looking for and test for its
presence in the result:

if (empname, ) in namelist:
    ... zie's there ...

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list