python 简单mysql工具类,使用连接池PooledDB案例

女生的网名这么多〃 提交于 2020-08-12 07:02:04

 # 环境 python3.7

# 第三方库安装:

pip install pymysql

pip install DBUtils

# 功能实现:建立mysql连接池,实现增删查改

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': '47.103.1.124',
        'port': 3306,
        'user': 'root',
        'passwd': '123456',
        'db': '37',
    }
    # 初始化工具类
    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("连接已关闭")

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!