[DB-SIG] Managing My Database Connections
Robert Rawlins - Tamed Technology
robert.rawlins at tamedtechnology.co.uk
Thu Mar 13 10:04:17 CET 2008
Hello Guys,
Well, thanks to Andy Todd I now know this to be the correct list to post on
so thought I would start a new thread with my question.
Essentially I only have a single database attached to my application but I'm
looking for the best way to handle its connection so thought I would come
and get your thoughts and opinions.
Within my applications I'll have many classes which access the database, I'm
wondering to what level I should extract the database connection.
Should I create a new database connection and close it for every method
which calls the database? Should I create the connection to the DB when I
construct the class and place the cursor in the self scope? Or should I
create an application wide connection to the database and inject the
connection into all the classes which require it?
At the moment I've created a singleton class which contains the connection
to the database, I then pass this class into my other objects and store it
as a property in the self scope. Then, for each function which needs to
access the database I create a new cursor and then close the cursor at the
end of the method, like so:
class someclass:
# I'm the constructor method
def __init__(self, connection):
# Create the connection
self.connection = connection
# Method which calls the database
def mymethod(self):
new_cursor = self.connection.cursor()
new_cursor.execute("""INSERT INTO......""")
new_cursor.close()
Is this the best way to handle things? I'm simply looking for the least
verbose and simple way to query the database.
Thanks for your advice and thoughts, I look forward to seeing how you guys
handle this.
Robert
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/db-sig/attachments/20080313/4bc31133/attachment.htm
More information about the DB-SIG
mailing list