un-tuple (newbie)

sdd daniels at dsl-only.net
Mon Dec 1 22:44:57 CET 2003

Martin Doering wrote:
> I want to use Jython to fetch exactly one value from a database query,
> like here:
> # execute a query
> def query(db, sql):
>     c = db.cursor()
>     c.execute(sql)
>     for line in c.fetchall():
>         val = line
           val, = line # one way
           (val,) = line # same as above (perhaps more readable?)
           val = line[0] # another way
>         print val
>     c.close()
>     return val

Personally, I'd call it "cursor", not "c".  Also my DB predeliction
leads me to prefer calling it a "row", not a "line".

If you know (and don't care to check) that a single row is returned,
with a single value, I might try something like this:

   def single_value_query(db, sql):
       cursor = db.cursor()
           return cursor.fetchone()[0]

More information about the Python-list mailing list