Mysql class works like php

gardsted gardsted at yahoo.com
Sun Oct 7 04:48:27 EDT 2007


Bruno Desthuilliers wrote:
> Andrey a écrit :
>> Hi
>>
>> just a quick question about using MySQL module... are there any api / 
>> class available to give a higher level in working with Mysql in python?
>> such as
>> db.fetch_array(),
>> db.fetch_rows(),
>> db.query(),
>> for eachrow in db.fetch_array():
>>     xxxx
> 
> You really find this "higher level" than Python's db-api ???
> 
>> just as easy as PHP?
> 
> D'oh :(
> 
> 
> // PHP:
> // suppose we have a valid $connection
> $q = mysql_query("select * from yaddayadda", $connection)
> if (is_resource($q)) {
>   while($row = mysql_fetc_row($q)) {
>     do_something_with($row);
>   }
>   mysql_free($q);
> }
> else {
>   // handle the error here
> }
> 
> # python:
> # suppose we have a valid connection
> cursor = connection.cursor() # can specify the kind of cursor here
> try:
>   cursor.execute("select * from yaddayadda")
> except MysqlError, e:
>   # handle error here
> else:
>   for row in cursor:
>     do_something_with(row)
> 
> # not strictly necessary, you can reuse the same
> # cursor for another query
> cursor.close()
> 
> 
> As far as I'm concerned, I fail to see how PHP is "higher level" or 
> "easier" here.
> 
> 

Maybe You should look into sqlalchemy.
I am also a newbie at that, but it allows you to do things like this 
(untested):
             sqltxt="""select * from mytable"""
             result=mysession.execute(sqltxt)
             for r in result.fetchmany():

which pretty good mimics the 'for eachrow in db.fetch_array():'

yours politely
jorgen





More information about the Python-list mailing list