Pyodbc 如果连接失败重试

Pyodbc if connection fails retry

您好,我有以下 python 代码连接到我的 SQL-Server DB

class CDBTools:
    details = {
        'server' : 'localhost',
        'database' : 'MyDB',
        'username' : 'me',
        'password' : 'myPass'
    }

    conn = None
    def __init__(self, server, database, username, password): 
        
        self.details["server"] = server
        self.details["database"] = database
        self.details["username"] = username
        self.details["password"] = password
           

    def connect_to_db(self):
        connect_string = 'DRIVER={{FreeTDS}};SERVER={server}; DATABASE={database};UID={username};PWD={password}'.format(**self.details)
        try:
            self.conn = pyodbc.connect(connect_string, autocommit=True)
            #print(connect_string)
            #Logger.Log(self.conn, "info")
        except pyodbc.Error as e:
            print(e, "error")
            
    def execute_select_query(self, query):
        try:
            curr = self.conn.cursor()
            out = curr.execute(query).fetchall()
        except pyodbc.IntegrityError as e:
            out = []
            print('ms-sql error: {0}'.format(e)) 
        except pyodbc.OperationalError as err: #Something happend with db, so try again
            out = []
            print('ms-sql Operation Error: {0}'.format(err))

        except AttributeError as err:
            out = []
            print('Connection to DB failed')
            pass
        try:
            curr.close()
        except:
            print('Connection to DB failed')
        return out

    def execute_inset_query(self, query):
        try:
            database_cursor = self.conn.cursor()
            database_cursor.execute(query)
        except pyodbc.DataError as e:
            print('ms-sql error: {0}'.format(e))
        except pyodbc.IntegrityError as e:
            print('ms-sql error: {0}'.format(e))
        except pyodbc.OperationalError as err: #Something happend with db, so try again
            print('ms-sql error: {0}'.format(e))

然后在我的主程序中我正在尝试这个并且它工作得很好,直到我断开网络

DBT = CDBTools("192.168.1.2\instance4", "my_db", "my_username", "my_passowrd")
DBT.connect_to_db()
while(True):
    print("[{0}]: {1}".format(time.strftime("%H:%M:%S"), DBT.execute_select_query("SELECT Name FROM Persons WHERE ID='1'")))

当我断开网络时,我没有收到任何错误,只是时间不再计算(当然是因为查询失败)但是当我重新连接网络时,查询再也不会成功了

所以有没有人知道我如何修改 execute_select_query 和 execute_inset_query 所以当与数据库的连接恢复时它将再次开始工作:)

感谢您的回答和最诚挚的问候

试试这个,它会在您每次使用 with 子句时连接,并在您离开时自动断开连接。

class CDBTools:
    details = {
        'server' : 'localhost',
        'database' : 'MyDB',
        'username' : 'me',
        'password' : 'myPass'
    }

    conn = None
    def __init__(self, server, database, username, password): 
        
        self.details["server"] = server
        self.details["database"] = database
        self.details["username"] = username
        self.details["password"] = password
           

    def connect_to_db(self):
        connect_string = 'DRIVER={{FreeTDS}};SERVER={server}; DATABASE={database};UID={username};PWD={password}'.format(**self.details)
        try:
            conn = pyodbc.connect(connect_string, autocommit=True)
            #print(connect_string)
            #Logger.Log(self.conn, "info")
        except pyodbc.Error as e:
            print(e, "error")

        return conn
            
    def execute_select_query(self, conn, query):
        try:
            curr = conn.cursor()
            out = curr.execute(query).fetchall()
        except pyodbc.IntegrityError as e:
            out = []
            print('ms-sql error: {0}'.format(e)) 
        except pyodbc.OperationalError as err: #Something happend with db, so try again
            out = []
            print('ms-sql Operation Error: {0}'.format(err))

        except AttributeError as err:
            out = []
            print('Connection to DB failed')
            pass

    def execute_inset_query(self, conn, query):
        try:
            database_cursor = conn.cursor()
            database_cursor.execute(query)
        except pyodbc.DataError as e:
            print('ms-sql error: {0}'.format(e))
        except pyodbc.IntegrityError as e:
            print('ms-sql error: {0}'.format(e))
        except pyodbc.OperationalError as err: #Something happend with db, so try again
            print('ms-sql error: {0}'.format(e))

然后:

DBT = CDBTools("192.168.1.2\instance4", "my_db", "my_username", "my_passowrd")

while True:
    with DBT.connect_to_db() as conn:
        print("[{0}]: {1}".format(time.strftime("%H:%M:%S"), DBT.execute_select_query(conn, "SELECT Name FROM Persons WHERE ID='1'")))

我可能会为 return 光标而不是连接创建一个方法。例如:

class CDBTools:
    details = {
        'server' : 'localhost',
        'database' : 'MyDB',
        'username' : 'me',
        'password' : 'myPass'
    }

    conn = None
    def __init__(self, server, database, username, password): 

        self.details["server"] = server
        self.details["database"] = database
        self.details["username"] = username
        self.details["password"] = password


    def get_cursor(self):
        connect_string = 'DRIVER={{FreeTDS}};SERVER={server}; DATABASE={database};UID={username};PWD={password}'.format(**self.details)
        try:
            conn = pyodbc.connect(connect_string, autocommit=True)
            #print(connect_string)
            #Logger.Log(self.conn, "info")
        except pyodbc.Error as e:
            print(e, "error")

        return conn.cursor()

DBT = CDBTools("192.168.1.2\instance4", "my_db", "my_username", "my_passowrd")

with DBT.get_cursor() as cursor:
    cursor.execute("SELECT Name FROM Persons WHERE ID='1'")
    for row in cursor.fetchall():
        print(row)

祝你好运!