[Tutor] Exceptions while dealing with MySQL

Alan Gauld alan.gauld at btinternet.com
Tue Apr 24 22:06:29 CEST 2007


"Thanos Panousis" <pthanos at gmail.com> wrote in

> I managed to get a class variable to hold a cursor via something 
> like
>
> class person:
>    cursor = MySQLdb.connect(stuff).cursor()
>
> BUT when I make a function inside my class called myConnect, where I
> do error checking and so on, I can't make it work:

Your Python OOP is a bit mixed up here.

> class person:
>    cursor = myConnect()
>
>    __init(self)___:
>        more things here....

You need to add def statements and the underscores
come before the parens

      def __init__(self)

>   myConnect(self):

Similarly here. BUT this is an instance method (via the self 
parameter),
it will not work at the class level.

>       try:
>             return MySQLdb.connect(stuff).cursor()
>       catch:

And this should be except not catch...

>              print "Error!"

> When trying to run this I get NameError: name 'myConnect' is not
> defined. Any pointers for my OO-blindness?

You can just make the connect call directly at the class level.

class Person:
     cursor = MySQLdb.connect(...).cursor()

You can then access it in your objects methods using either

self.cursor
or
Person.cursor

Personally I prefer the second since it makes it clear its a
class variable...

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list