python-mysql数据库操作封装

发布时间:2019-09-25 08:21:37编辑:auto阅读(1685)

    前言:最近在学python,学到有关数据库的操作之时,想着把数据库的配置抽离出来,下面把代码贴出来~

    db_config.py

    class mysql_config():
    
        def get_config(self, name):
            config = {
                'testdb': {
                    'host': '127.0.0.1',
                    'user': 'root',
                    'password': '123',
                    'database': 'test',
                    'port': 3306
                }
            }
            return config[name]

    通过config这个dict,用name去检索配置,一般数据库的配置分测试服(开发)数据库还有正式服数据库


    db_mysql

    import mysql.connector
    from db_config import mysql_config
    m_config = mysql_config()
    
    
    class db_mysql_detail():
    
        def __init__(self, name):
            self.__name = name
            self.__conn = self.build_conn(name)
            self.__cursor = self.__conn.cursor()
    
        @property       
        def conn(self):
            return self.__conn
    
        def build_conn(self, name):
            try:
                config = m_config.get_config(name)
                con = mysql.connector.connect(**config)
                return con
            except mysql.connector.Error as err:
                print('Something wrong: %s' % format(err))
    
    
        def getAll(self,sql):
            self.__cursor.execute(sql)
            return self.__cursor.fetchall()
    
        def close(self):
            pass
    

    使用pip下载mysql包,import类mysql.connector


    assist.py

    from db_mysql import db_mysql_detail
    
    obj = db_mysql_detail('testdb')
    sql = 'select * from user'
    data = obj.getAll(sql)
    print(data)

    进行测试

关键字