[Tutor] Database queries returning indexes rather than strings...

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 22 Mar 2002 13:58:44 -0800 (PST)


On Fri, 22 Mar 2002, Israel Evans wrote:

>  I'm using the MySQLdb module recently mentioned here and I'm running
> into issues of trying to interpret the results of my queries.  It's
> seems after having made a connection and a cursor when I try to execute
> a query I get the answer to that query back as binary character or at
> least a Long integer or something.  It comes back to me a a number
> followed by an L.

Yes, this is telling us the number of rows that were either affected or
found by the execute().  To actually traverse through the results, we can
use the fetchone() or fetchall() method.  Here's a quicky interactive
session with MySQLdb:

###
>>> import MySQLdb
>>> conn = MySQLdb.connect(db='test')
>>> cursor = conn.cursor()
>>> cursor.execute("create table foobar (name varchar(20))")
0L
>>> cursor.execute("insert into foobar values ('evans')")
1L
>>> cursor.execute("insert into foobar values ('danny')")
1L
>>> cursor.execute("select * from foobar")
2L
>>> cursor.fetchone()
('evans',)
>>> cursor.fetchone()
('danny',)
>>> cursor.fetchone()
>>> cursor.execute("select * from foobar")
2L
>>> cursor.fetchall()
(('evans',), ('danny',))
##

That's basically it.  *grin* No, there's a little more to it, and you can
take a look at the Python/DB API 2.0 docs:

    http://www.python.org/topics/database/DatabaseAPI-2.0.html

for the details.  You might also want to look at amk's explanation of the
API itself:

    http://www.amk.ca/python/writing/DB-API.html



MySQLdb should also come with its own set of documentation and examples in
the source code; check the "docs" directory in the source directory, and
you should see it.


Please feel free to ask more questions.  Database stuff can be really
exciting when it starts working.  *grin* Good luck!