【问题标题】:Pyodbc if connection fails retryPyodbc 如果连接失败重试
【发布时间】:2020-12-15 00:01:58
【问题描述】:

您好,我有以下 python 代码可以连接到我的 SQL-Server 数据库

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 以便在恢复到数据库的连接时它会再次开始工作:)

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

【问题讨论】:

    标签: python pyodbc freetds


    【解决方案1】:

    试试这个,每次使用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'")))
    

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

    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)
    

    祝你好运!

    【讨论】:

      猜你喜欢
      • 2019-02-21
      • 1970-01-01
      • 2018-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 2019-11-16
      • 1970-01-01
      相关资源
      最近更新 更多