Single Database Connection Throughout The Python Application
Single Database Connection Throughout The Python Application
0
My Question is what is the best way to maintain the single database connection in the entire
application? Using Singleton Pattern? How?
Conditions that are needed to be taken care of:
The driver to my Database is not supported by the Django ORM. And due to same driver related issues, I am
using pyodbc to connect to the database. Right now I am having below class for creating and managing the DB
connections:
class DBConnection(object):
def __init__(self, driver, serve,
database, user, password):
self.driver = driver
self.server = server
self.database = database
self.user = user
self.password = password
def __enter__(self):
self.dbconn = pyodbc.connect("DRIVER={};".format(self.driver) +\
"SERVER={};".format(self.server) +\
"DATABASE={};".format(self.database) +\
"UID={};".format(self.user) +\
"PWD={};".format(self.password) + \
"CHARSET=UTF8",
# "",
ansi=True)
return self.dbconn
0
For now, I am going ahead with the singleton class approach. Anyone seeing the potential flaws in this, feel to
mention them :)
self.driver = driver
self.server = server
self.database = database
self.user = user
self.password = password
self.dbconn = None
@classmethod
def execute_query(cls, query):
"""execute query on singleton db connection"""
connection = cls.get_connection()
try:
cursor = connection.cursor()
except pyodbc.ProgrammingError:
connection = cls.get_connection(new=True) # Create new connection
cursor = connection.cursor()
cursor.execute(query)
result = cursor.fetchall()
cursor.close()
return result
shareimprove this answer
answered Nov 11 '16 at 6:55
Moinuddin Quadri
29.7k55082
You should make sure that a connection is not shared between threads, or you might run into some surprising and
hard-to-debug behaviour. You can save the connection on a threading.local() object so that each thread has
it's own singleton connection. – knbk Nov 11 '16 at 11:12
@knbk: I am just sharing the connection object, but creating a new local cursor for each query
in execute_query function. So, since query/result relationship are maintained by the cursor, I do not see any harm
even if execute_query is called asynchronously. That is again my assumption. Or I am wrong? – Moinuddin
Quadri Nov 11 '16 at 11:55
1
From the pyodbc docs: "threadsafety The integer 1, indicating that threads may share the module but not
connections. Note that connections and cursors may be used by different threads, just not at the same time." -- So
you can't share the connection between threads that try to access the database concurrently. – knbk Nov 11 '16 at
12:42