Return type (value) of cursor.fetchall()

2,650 views
Skip to first unread message

Nader

unread,
Jan 16, 2008, 8:14:24 AM1/16/08
to Django users
Hallo,

I have a customize statement in my model to set some query.

cursor.execute(""
SELECT count(*) FROM ingestQueue
WHERE timeOfEntry > (subdate( (SELECT
max(timeOfLaststatusupdate)
FROM ingestQueue WHERE status =
'done'), interval 1 hour))
AND status = 'done';
""")

We can get the result of this statement in "cursor.fetchall()'. Is
this result a integer because of "SELECT count(*)"?
Or I have to iterate the "cursor.fetchall()"!

Cheers,
Nader

Karen Tracey

unread,
Jan 16, 2008, 10:18:37 AM1/16/08
to django...@googlegroups.com

For an authoritative answer, consult the Python DB API spec, which defines what fetchall() returns:

http://www.python.org/dev/peps/pep-0249/

it says: "Fetch all (remaining) rows of a query result, returning them as a sequence of sequences ( e.g. a list of tuples)."

So, fetchall() will be returning a sequence of tuples.  But since you are selecting COUNT(*) you know you are going to get only one row, with one value in that row.  So I believe it would be safe to just do a fetchone() and save yourself one layer of sequencing.  You'll still need to unpack the count value from the single row tuple.  These things are easy to figure out with a little experimenting under  "python manage.py shell":

>>> from django.db import connection
>>> cursor = connection.cursor()
>>> cursor.execute("SELECT COUNT(*) From Clues")
1L
>>> fa = cursor.fetchall ()
>>> fa
((905815L,),)
>>> cursor.execute("SELECT COUNT(*) From Clues")
1L
>>> fo = cursor.fetchone()
>>> fo
(905815L,)
>>> counta = fa[0][0]
>>> counta
905815L
>>> counto = fo[0]
>>> counto
905815L

Karen
Reply all
Reply to author
Forward
0 new messages