# -*- coding: utf-8 -*- """ MySQL client """ import logging import sys import MySQLdb log = logging.getLogger(__name__) class MyDB: """ MySQL client """ host = "" user = "" pwd = "" db = "" con = 0 def __init__(self, host, user, pwd, db): self.host = host self.user = user self.pwd = pwd self.db = db def connect(self): """ Connect to MySQL server """ if self.con == 0: try: con = MySQLdb.connect(self.host, self.user, self.pwd, self.db) self.con = con except Exception: log.fatal('Error connecting to MySQL server', exc_info=True) sys.exit(1) def doSQL(self,sql): """ Run INSERT/UPDATE/DELETE/... SQL query """ cursor = self.con.cursor() try: cursor.execute(sql) self.con.commit() return True except Exception: log.error('Error during SQL request "%s"', sql, exc_info=True) self.con.rollback() return False def doSelect(self, sql): """ Run SELECT SQL query and return result as dict """ cursor = self.con.cursor() try: cursor.execute(sql) return cursor.fetchall() except Exception: log.error('Error during SQL request "%s"', sql, exc_info=True) return False