Saturday, June 27, 2009

Python: Simple Singleton for Mysql Access

I was trying to come up with a simple implementation of Singleton pattern in python, its a bit different from other language constructs. Here is the code implementing a single point database access using MySQLdb.

#! /usr/bin/python

import MySQLdb
import sys

class Conn(object):
__instance = None
__conn = None


def __init__(self):
try:
if Conn.__instance == None:

Conn.__instance = self
Conn.__conn = MySQLdb.connect (host="localhost", user="user", passwd="pass", db="dbname")

except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])

sys.exit(1)


def get_connection(self):
return Conn.__conn


if __name__ == "__main__":
conn = (Conn()).get_connection()

''' Do your thing '''
conn.close()


It's not perfect I guess, but right now it serves the purpose. You are welcome to put down any valuable advice into this.

Back to Blogging

After a failed attempt last year to get back to blogging, I'm trying it again this year. I really wanted to get back, but got busy will...