python封装的mysql数据库连接操作基类(BaseDao)(使用pymysql库)

标题pymysql模块封装的数据库操作基类

 # 引入pymysql
import pymysql
import json
import logging
import os

class BaseDao(): # DAO: database access object

    def __init__(self, configFile='pymysql.json'):
        self.__connection = None
        self.__cursor = None
        self.__config = json.load(open(os.path.dirname(__file__) + os.sep + configFile, 'r'))  # 通过json配置获得数据的连接配置信息
        print(self.__config)
        pass

    # 获取数据库连接的方法
    def getConnection(self):
        # 当有连接对象时,直接返回连接对象
        if self.__connection:
            return self.__connection
        # 否则通过建立新的连接对象
        try:
            self.__connection = pymysql.connect(**self.__config)
            return self.__connection
        except pymysql.MySQLError as e:
            print("Exception:" + str(e))
            pass
        pass

    # 用于执行sql语句的通用方法 # sql注入
    def execute(self, sql, params):
        try:
            self.__cursor = self.getConnection().cursor()
            # result返回sql语句影响到的条数
            if params: # 带参数sql语句
                result = self.__cursor.execute(sql, params)
            else:      # 不带参数sql语句
                result = self.__cursor.execute(sql)
            return result
        except (pymysql.MySQLError, pymysql.DatabaseError, Exception) as e:
            print("出现数据库访问异常:" + str(e))
            self.rollback()
            pass
        finally:
            pass
        pass

    def fetch(self):
        if self.__cursor:
            return self.__cursor.fetchall()
        pass

    def commit(self):
        if self.__connection:
            self.__connection.commit()
        pass

    def rollback(self):
        if self.__connection:
            self.__connection.rollback()
        pass

    # 返回最后的自增主键
    def getLastRowId(self):
        if self.__cursor:
            return self.__cursor.lastrowid
        pass

    def close(self):
        if self.__cursor:
            self.__cursor.close()
        if self.__connection:
            self.__connection.close()
        pass

    pass

标题使用JSON写的配置参数文件:

‘pymysql.json’
{“host”:“127.0.0.1”, “user”:“root”,“password”:“root”, “database”:“db_test_shop1”, “port”:3306, “charset”:“utf8”}

你可能感兴趣的:(python封装的mysql数据库连接操作基类(BaseDao)(使用pymysql库))