gpt4 book ai didi

python - 在python中打开一个新数据库之前检查是否存在与数据库的连接

转载 作者:行者123 更新时间:2023-11-28 20:36:34 25 4
gpt4 key购买 nike

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 上的现有数据库。有没有一种方法可以检查连接是否已打开,如果是,则返回现有连接而不是打开新连接?

最佳答案

您可以为此使用描述符:

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

关于python - 在python中打开一个新数据库之前检查是否存在与数据库的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44855399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com