howmuch515 icon

mysql_manager_template.py

howmuch515 | PRO | 06/22/19 01:36:55 PM UTC | 0 ⭐ | 288 👁️ | Never ⏰ | []
Python |

1.36 KB

|

None

|

0 👍

/

0 👎

import configparser
import logging
import MySQLdb
 
DB_CONFIG_FILE = "./settings/dbinfo.ini"
logging.basicConfig(level=logging.DEBUG)
 
 
class DBManager():
    def __init__(self):
        config = self.loadConfig(DB_CONFIG_FILE)
        self.host = config["HOST"]
        self.port = config["PORT"]
        self.user = config["USER"]
        self.passwd = config["PASSWD"]
        self.db_name = config["DB_NAME"]
        self.table_name = config["TABLE_NAME"]
 
        # connect DB
        self.conn = self.connectDB()
        self.cur = self.conn.cursor(MySQLdb.cursors.DictCursor)
 
    def __del__(self):
        self.cur.close()
        self.conn.close()
 
    def loadConfig(self, db_config_file):
        try:
            parser = configparser.ConfigParser()
            parser.read(db_config_file)
            return parser['mysql']
 
        except Exception as e:
            logging.critical("Load DB Config error")
            logging.critical(e)
 
    def connectDB(self):
        try:
            conn = MySQLdb.connect(
                host=self.host,
                port=int(self.port),
                user=self.user,
                passwd=self.passwd,
                db=self.db_name,
            )
            return conn
        except Exception as e:
            logging.critical("Connect DB error")
            logging.critical(e)

Comments