rowcount in dbi w/ odbc

Steve Holden sholden at holdenweb.com
Mon Apr 8 11:09:35 EDT 2002


"don" <donald.braman at yale.edu> wrote in message
news:a8iv0i$56r$1 at news.ycc.yale.edu...
> I'm new to Python programming. I am trying to gain access to specific
> columns in specific rows in an Access database, but am not having much
luck.
> I thought I'd first try to access specific rows and columns. However, when
I
> try to use "rowcount" to see how many rows there are, I get
"AttributeError:
> rowcount". I assume there is some easy way to do this, but I can't seem to
> figure it out. Here's my attempt that fails:
>
> import dbi, odbc
> try:
>         con = odbc.odbc('mydatabase')
>         cur = con.cursor()
>         cur.execute('SELECT * FROM mytable')
>         con.close()
>
>         for row in range(0, cur.rowcount()-1):
>                 for col in range(0, cur.colCount()-1):
>                         print cur.getField(row, col), ',',
>                 print cur.getField(row, col)
>
> except NameError,e:
>         print 'error ', e, 'undefined'
>
Note that the odbc module is not fully conformant to the Python DB API, but
that even conformant modules do not have to implement rowcount. It's
explicitly stated that the value rowcount provides may change as access to
the retrieved data takes place.

>
> I suppose I should note that I can access the data using the following,
but
> that it doesn't give me access to a specific rows:
>
> import dbi, odbc
> try:
>     s = odbc.odbc('mydatabase')
>     cur = s.cursor()
>     cur.execute('SELECT * FROM mytable)
>     print cur.description
>     for tup in cur.description:
>         print tup[0],
>     print
>     while 1:
>         rec = cur.fetchmany(1)
>         if not rec: break
>         print rec
>
> except NameError,e:
>         print 'error ', e, 'undefined'
>
The easiest way is to use the returned data to answer your questions, with
code like what follows.

    cur.execute("SELECT * FROM mytable")
    data = cur.fetchall()
    print "Row count is", len(data)

Then handle the rows with something like

    for row in data:
        print "Column zero is", row[0]

If you need the database to explain the structure of the data, again you
should be aware that not all modules and database make a complete
description of hte returned data available. Take a look at

    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81189

for one way to get some insight into the structure of a query's output.

regards
 Steve







More information about the Python-list mailing list