如何在django中检查数据库是否关闭

wixjitnu  于 2023-03-09  发布在  Go
关注(0)|答案(1)|浏览(89)
from django.db import connections
from django.db.utils import OperationalError
db_conn = connections['default']
try:
    c = db_conn.cursor()
except OperationalError:
    connected = False
else:
    connected = True

在服务器中我没有关闭连接,但是无法更新查询,它显示数据库连接已关闭。在django中是否有任何解决方案来检查数据库是否已关闭

67up9zun

67up9zun1#

试试这个

def connected():
    """Context manager that ensures we're connected to the database.

    If there is not yet a connection to the database, this will connect on
    entry and disconnect on exit. Preexisting connections will be left alone.

    If the preexisting connection is not usable it is closed and a new
    connection is made.
    """
    if connection.connection is None:
        connection.close_if_unusable_or_obsolete()
        connection.ensure_connection()
        try:
            yield
        finally:
            connection.close()
    elif connection.is_usable():
        yield
    else:
        # Connection is not usable, so we disconnect and reconnect. Since
        # the connection was previously connected we do not disconnect this
        # new connection.
        connection.close_if_unusable_or_obsolete()
        connection.ensure_connection()
        yield

相关问题