python 基于mysql第三方库的封装函数,便于调用

4 篇文章 1 订阅
import pymysql
import time
from DBUtils.PooledDB import PooledDB


class MysqldbHelper(object):  # 继承object类所有方法
    def __init__(self, config):
        self.host = config['host']
        self.username = config['user']
        self.password = config['passwd']
        self.db = config['db']
        self.port = config['port']
        while True:
            try:
                self.pool = PooledDB(pymysql, 5, host=self.host, user=self.username, passwd=self.password, db=self.db,
                                     port=self.port,
                                     cursorclass=pymysql.cursors.DictCursor)
            except BaseException as e:
                print(e)
                self.pool = None
            if self.pool:
                print("mysql连接成功")
                break
            print("连接失败,5秒后重试")
            time.sleep(5)

    # # 从连接池获取一条连接
    def get_conn(self):
        conn = self.pool.connection()
        cur = conn.cursor()  # 光标
        return conn, cur

    # 关闭连接
    def close_conn(self, conn, cur):
        cur.close()
        conn.close()

    def deal_with_sql(self, cur, conn, SQL, types='SELECT'):
        if types == "SELECT":
            cur.execute(SQL)
            result = cur.fetchall()
            return result
        elif types == "INSERT":
            try:
                cur.execute(SQL)
                conn.commit()  # 提交事务
                return True
            except BaseException as e:
                print("插入失败:", e)
                return False
        elif types == "UPDATE":
            try:
                cur.execute(SQL)
                conn.commit()
                return True
            except BaseException as e:
                print("更新失败:", e)
                return False
        elif types == "DELETE":
            try:
                cur.execute(SQL)
                conn.commit()
                return True
            except BaseException as e:
                print("删除失败:", e)
                return False
        else:
            return None


if __name__ == '__main__':
    config = {
        'host': '127.0.0.01',
        'port': 3306,
        'user': 'root',
        'passwd': '123456',
        'db': 'ceshi',
    }
    # 初始化工具类
    mydb = MysqldbHelper(config)
    # 从连接池获取连接
    conn, cur = mydb.get_conn()

    # 执行查询sql
    SQL = """select * from ceshi2"""
    result = mydb.deal_with_sql(cur, conn, SQL)
    print(result)

    # 执行插入sql
    SQL2 = """INSERT INTO ceshi2  (a,b,c) VALUES (12,11,34)"""
    result2 = mydb.deal_with_sql(cur, conn, SQL2, "INSERT")
    print(result2)
    # 关闭连接
    mydb.close_conn(conn, cur)
    print("连接已关闭")
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值