[Tutor] python classes and mysql

Magnus Lycka magnus@thinkware.se
Wed, 14 Aug 2002 03:11:00 +0200


At 09:40 2002-08-13 -0400, rickp@telocity.com wrote:
>If I create multiple classes in python to deal with different aspects of
>a program and each of those classes needs to access mysql what is the
>best way of handling connections/cursors?
>
>1) Each class opens a connection and creates a cursor.
>2) The toplevel opens a connection which is passed to the class which
>    then creates a cursor.
>3) The toplevel opens a connection and creates a cursor which is passed
>    to the class.

I don't think there is a universal answer to this.
There are several issues involved. Here are a few:

Opening and closing connections to databases is typically
rather slow. Reuse connections if you can.

Transactions follow connections in the DB-API. If you have
several simultaneous cursors for a connection, you can't
commit and rollback the cursors independently. In other
words, at any one time, a connection can only be involved
in one transaction!

It's usually a good idea to honour the KISS principle.
(Keep It Simple, Stupid.)

Object and Class structures can look different. I'm not
sure what you mean by "toplevel" above. Inheritence or
aggregation? An object than encapsulates the connection
can be passed as a parameter or accessed as a singleton
etc. One could imagine a connection wrapper which is
used to get cursors from. (A cursor factory in other
words). Maybe it will make a connection the first time
someone requests a cursor? Maybe the application keeps
tracks of some kind of transaction ids and the cursor
factory can figure out when it needs to make a new
connection and when it can reuse an old one.

If a program is to use several different database
modules, the connection parameters (as well as some
other stuff) might vary, and those varying things
should be encapsulated in a single place in the code.


--=20
Magnus Lyck=E5, Thinkware AB
=C4lvans v=E4g 99, SE-907 50 UME=C5
tel: 070-582 80 65, fax: 070-612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se