Guest User

Untitled

a guest
Sep 7th, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. import MySQLdb
  3. import _mysql_exceptions
  4. import time
  5.  
  6.  
  7. class AutoconnectDB():
  8.  
  9. def __init__(self,user,password,db,host=None,unix_socket=None):
  10. self.__user = user
  11. self.__password = password
  12. self.__db = db
  13.  
  14. def __connect(self):
  15. self.__conn = MySQLdb.connect(user=self.__user, passwd=self.__password, db=self.__db, unix_socket="/var/lib/mysql/mysql.sock", connect_timeout=1)
  16. self.__conn.autocommit(True)
  17.  
  18. def doQuery(self,query,input=None,max_retry=5): # tries to do query, auto-reconnect on failure
  19.  
  20. tries = 0
  21. cursor = None
  22.  
  23. while tries < max_retry:
  24.  
  25. try:
  26. cursor = self.__conn.cursor(MySQLdb.cursors.DictCursor)
  27. cursor.execute(query,input)
  28. break
  29.  
  30. except (MySQLdb.OperationalError,AttributeError): # db.OpErr = Last connection was cool and good, but the server disconnected since, Attr = self.__conn is None (not connected yet)
  31.  
  32. try:
  33. self.__connect()
  34.  
  35. except _mysql_exceptions.OperationalError: # connection failed
  36. pass
  37.  
  38. if tries > 0: # not the first connection attempt
  39. time.sleep(0.5)
  40.  
  41. tries += 1
  42.  
  43. return cursor
Add Comment
Please, Sign In to add comment