我的问题是在整个应用程序中维护单个数据库连接的最佳方法是什么? 使用Singleton Pattern?怎么样?的
需要注意的条件:
Django ORM不支持我的数据库的驱动程序。由于相同的驱动程序相关问题,我使用pyodbc
连接到数据库。现在我正在创建和管理数据库连接的下层课程:
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
def __exit__(self, exc_type, exc_val, exc_tb):
self.dbconn.close()
但这种方法的问题是它将为每个查询创建新的数据库连接。按照单例模式进行此操作的更好方法是什么?如果连接关闭,我能想到的方式将保持对连接的引用。类似的东西:
def get_database_connection():
conn = DBConnection.connection
if not conn:
conn = DBConnection.connection = DBConnection.create_connection()
return conn
实现这一目标的最佳方法是什么?有任何建议/想法/例子吗?
PS:我正在检查使用weakref
,它允许创建对象的弱引用。我认为使用weakref
和单例模式来存储连接变量是个好主意。这样,在不使用DB时,我不必保持连接alive
。你们对此有何看法?
答案 0 :(得分:0)
目前,我正在采用单身人士的方法。任何人都看到了这方面的潜在缺陷,请提及:)
用于创建连接的 DBConnector
类
class DBConnector(object):
def __init__(self, driver, server, database, user, password):
self.driver = driver
self.server = server
self.database = database
self.user = user
self.password = password
self.dbconn = None
# creats new connection
def create_connection(self):
return 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)
# For explicitly opening database connection
def __enter__(self):
self.dbconn = self.create_connection()
return self.dbconn
def __exit__(self, exc_type, exc_val, exc_tb):
self.dbconn.close()
用于管理连接的 DBConnection
类
class DBConnection(object):
connection = None
@classmethod
def get_connection(cls, new=False):
"""Creates return new Singleton database connection"""
if new or not cls.connection:
cls.connection = DBConnector().create_connection()
return cls.connection
@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
答案 1 :(得分:0)
class DBConnector(object): def __new__(cls): if not hasattr(cls, 'instance'): cls.instance = super(DBConnector, cls).__new__(cls) return cls.instance def __init__(self): #your db connection code in constructor con = DBConnector() con1 = DBConnector() con is con1 # output is True Hope, above code will helpful.