python-mysql数据库连接工具类封装

import pymysql


class DBUtil:

    def __init__(self, database):
        self.db = pymysql.connect(host='XXXXX', port=XXXX, user='XXXX', password="XXXX",
                                  database=database)
        self.cursor = self.db.cursor()

    def query_one(self, sql):
        """查询单条数据"""
        result = None
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchone()
            self.cursor.close()
        except Exception as e:
            print(e)
        return result

    def query_all(self, sql):
        """查询多条数据"""
        list_result = ()
        try:
            self.cursor.execute(sql)
            list_result = self.cursor.fetchall()
            self.cursor.close()
        except Exception as e:
            print(e)
        return list_result

    def insert(self, sql):
        """新增数据"""
        return self.__edit(sql)

    def update(self, sql):
        """更新数据"""
        return self.__edit(sql)

    def delete(self, sql):
        """删除数据"""
        return self.__edit(sql)

    def __edit(self, sql):
        count = 0
        try:
            count = self.cursor.execute(sql)
            self.db.commit()
            self.cursor.close()
        except Exception as e:
            print(e)
        return count


if __name__ == '__main__':
    db = DBUtil(database='qf_marketing_usercenter_test')
    # sql = 'select * from org_company '
    sql = 'update org_company set deleted = 0 where companyUuid = "9898bd08-8u5-4899-ab69-5300e87e3b68"'
    data = db.update(sql=sql)
    print(data)

 

posted @ 2022-03-22 20:39  lwjnicole  阅读(1016)  评论(0编辑  收藏  举报