Moi*_*dri 5 python django singleton database-connection pyodbc
我的问题是在整个应用程序中维护单个数据库连接的最佳方法是什么? 使用单例模式?如何?
需要注意的条件:
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()
Run Code Online (Sandbox Code Playgroud)
但是这种方法的问题在于它会为每个查询创建新的数据库连接。遵循单例模式的更好方法是什么?如果连接关闭,我能想到的方式将保留对连接的引用。就像是:
def get_database_connection():
conn = DBConnection.connection
if not conn:
conn = DBConnection.connection = DBConnection.create_connection()
return conn
Run Code Online (Sandbox Code Playgroud)
实现这一目标的最佳方法是什么?任何建议/想法/例子?
PS:我正在检查 using weakrefwhich 允许创建对对象的弱引用。我认为weakref与单例模式一起使用来存储连接变量是个好主意。这样我就不必alive在不使用 DB 时保持连接。大家对此有什么看法?
现在,我将继续使用单例类方法。任何看到其中潜在缺陷的人都可以提及它们:)
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()
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11887 次 |
| 最近记录: |