python之pymysql的使用

#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@author: yunhgu
@time:   2021/4/29 9:10
@file:   MysqlClient.py
@description: connect with mysql and option it
"""
import pymysql
from bin.LogTool import log

logger = log()


class MysqlClient:
    def __init__(self, host, port, user, password, db):
        try:
            # 创建一个连接数据库的对象
            self.conn = pymysql.connect(host=host, port=port, user=user, password=password, database=db, charset='utf8',
                                        cursorclass=pymysql.cursors.DictCursor)
            # 使用cursor()方法创建一个游标对象,用于操作数据库
            self.cur = self.conn.cursor()
        except Exception as e:
            print(f"MysqlClient init error : {e}")
            logger.error('MysqlClient init error : %s', e)

    # 查询数据
    def search(self, sql):
        try:
            self.cur.execute(sql)
            result = self.cur.fetchall()
        except Exception as e:
            print(f'MysqlClient search error : {e}')
            logger.error('MysqlClient search error : %s', e)
            return None
        return result

    # 插入数据
    def insert(self, sql):
        try:
            self.cur.execute(sql)  # 执行sql
            self.conn.commit()  # 增删改操作完数据库后,需要执行提交操作
        except Exception as e:
            print(f'MysqlClient insert error : {e}')
            logger.error('MysqlClient insert error : %s', e)
            # 发生错误时回滚
            self.conn.rollback()
            logger.info('MysqlClient insert error but had rollback: %s', sql)
            return False
        return True

    # 更新数据
    def update(self, sql):
        try:
            self.cur.execute(sql)  # 执行sql
            self.conn.commit()  # 增删改操作完数据库后,需要执行提交操作
        except Exception as e:
            print(f'MysqlClient update error : {e}')
            logger.error('MysqlClient update error : %s', e)
            # 发生错误时回滚
            self.conn.rollback()
            logger.info('MysqlClient update error but had rollback: %s', sql)
            return False
        return True

    # 删除数据
    def delete(self, sql):
        try:
            self.cur.execute(sql)  # 执行sql
            self.conn.commit()  # 增删改操作完数据库后,需要执行提交操作
        except Exception as e:
            print(f'MysqlClient delete error : {e}')
            logger.error('MysqlClient delete error : %s', e)
            # 发生错误时回滚
            self.conn.rollback()
            logger.info('MysqlClient delete error but had rollback: %s', sql)
            return False
        return True


if __name__ == '__main__':
    mysql = MysqlClient('127.0.0.1', 3306, 'root', '123456', 'uat_mq')
    mysql.insert("INSERT INTO exchanges(virtual_host,exchange_name,exchange_type,\
    create_time,state,info) VALUES('uat','exchange_name_02','fanout',NOW(),'using','info message');")
    result = mysql.search('select * from exchanges')
    print(result)

 

posted @ 2021-05-06 10:17  不能说的秘密  阅读(106)  评论(0编辑  收藏  举报