import dataset
class db(object):
_db_connection = None
_db_cur = None
def __init__(self):
self._db_connection = dataset.connect(path_to_database)
def __del__(self):
self._db_connection.executable.close()
在上面的代码中,我创建了一个连接到AWS上现有数据库的类。有没有办法可以检查连接是否已经打开,如果是,返回现有连接而不是打开新连接?
答案 0 :(得分:3)
您可以使用描述符:
class DBConn(object):
conn = None
def __get__(self, instance, owner):
if instance is None:
return self
if self.conn is None or self.conn.closed():
# Since this is a class attribute, it is shared by all instances
self.conn = dataset.connect(path_to_database)
return self.conn
def __delete__(self, instance):
self.conn.executable.close()
self.conn = None
然后将其用作财产:
class DB(object):
connection = DBConn()
db = DB()
db.connection.do_something() # Opens a new connections
other_db = DB()
other_db.connection.do_something_else() # Reuses same connection
del db.connection # Closes the connection
other_db.connection.another_thing() # Reopens the connection
答案 1 :(得分:2)
它被称为Singleton模式看看: http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Singleton.html
class OnlyOne(object):
class __OnlyOne:
def __init__(self):
self.val = None
def __str__(self):
return `self` + self.val
instance = None
def __new__(cls): # __new__ always a classmethod
if not OnlyOne.instance:
OnlyOne.instance = OnlyOne.__OnlyOne()
return OnlyOne.instance
def __getattr__(self, name):
return getattr(self.instance, name)
def __setattr__(self, name):
return setattr(self.instance, name)
答案 2 :(得分:1)
在连接时,如果驱动程序无法连接,则可能会出现异常
因此您需要将您的连接呼叫包装到
中class db(object):
_db_connection = None
_db_cur = None
def __init__(self):
try:
self._db_connection = dataset.connect(path_to_database)
except WhateverExceptionYourDBDriverThrowsOnError:
pass
def __del__(self):
if self._db_connection:
self._db_connection.executable.close()
你没说什么驱动程序,你使用什么数据库,所以这是通用代码。您需要将Exception类型替换为驱动程序抛出的正确类型。
答案 3 :(得分:1)
db.local.conn.closed # return True or False
我在此post
中使用它