Documentation, assignment in expression.

Tim Chase python.list at tim.thechases.com
Mon Mar 26 06:14:01 EDT 2012


On 03/25/12 17:59, Dennis Lee Bieber wrote:
> On Sun, 25 Mar 2012 08:48:31 -0500, Tim Chase
>> Yeah, it has the same structure internally, but I'm somewhat
>> surprised that the DB connection object doesn't have an
>> __iter__() that does something like this automatically under the
>> covers.
>>
> 	I believe being able to use the connection object directly for
> queries is considered a short-cut feature... If you use the longer form
>
> con = db.connect()
> cur = con.cursor()
>
> 	the cursor object, in all that I've worked with, does function for
> iteration
>
> 	for rec in cur:
> 		#do stuff

Interesting.  Either this is something special for a particular 
DB back-end, or has been added since I went hunting (back with 
mxODBC and Python2.4).  I wouldn't be surprised if the latter was 
the case, as my code is nigh identical to yours.

  conn = db.DriverConnect(connection_string)
  cursor = conn.cursor()
  cursor.execute(sql, params)
  for row in cursor: # in the above 2.4 + mxODBC, this fails
    process(row)

I'd be interested to know the underlying implementation's 
efficiency, hopefully using .fetchmany() under the hood.  My 
understanding is that the .fetchmany() loop is the best way to do 
it, as the .fetchone() gets chatty with the DB (but is more 
efficient if you only need one row from a multi-result query), 
and the .fetchall() can blow out memory on large datasets.

-tkc







More information about the Python-list mailing list