can i set up a mysql db connection as a class ?
*binarystar*
newsgroup_mail... at ...binarystar.org
Fri Apr 28 01:54:20 EDT 2006
your on the right track ... create something like this ( hope the formatting doesn't go to hay wire )
class DB_Connector(object):
""" Humble Database Connection Class """
def __init__(self, host="localhost", user="MyUser",passwd="MyPassword", **other_db_arguments):
self.host = host
self.user = user
self.passwd = passwd
# Unpack Other Database Arguments Here
self.CreateConnection()
def CreateConnection( self ):
self.cursor = MySQLdb.connect(self.host, self.user, self.passwd)
def DestroyConnection( self ):
self.cursor.close()
def Execute( self, sql_statement ):
self.cursor.Execute( sql_statement )
return self.cursor.FetchAll()
Then when you run your program create an instance of the object
db_connection = DB_Connector( 'localhost', 'administrator', 'betelgeuse99', auto_commit=1, other_keyword_arg="yes" )
now when you pass the db_connection instance to other classes, a copy will be made automagically
thread_1_instance = ThreadingClass( db_connection )
thread_2_instance = ThreadingClass( db_connection )
thread_3_instance = ThreadingClass( db_connection )
should work ..
I hope this is useful
nephish at xit.net wrote:
> This is great !
>
> ok, i dont really have a lot of time to get into the ORMS (before your
> post, this is the first i have heard of it) and my stuff is due on
> Monday. he he.
>
> but, if i am able to make a global db connection, and multiple cursors
> pointing to the same connection object, how do i pull that off without
> making new db connections?
>
> something like
> class db(self):
> def __init__(self):
> db = MySQLdb.connect(host="localhost", user="MyUser",
> passwd="MyPassword",
> db="Stuff")
> def cursor(self):
> cursor = db.cursor()
> return cursor
>
>
> then have in my threads that need to connect
>
> cursor = db.cursor()
> cursor2 = db.cursor()
>
> and so on ? i may be way outta whack here. i am still new at classes,
> methods, and modules.
> i do have Essential Reference on the way from Amazon though ! :)
>
> thanks again
>
More information about the Python-list
mailing list