mysql连接池实例

环境:

        Python 3.8.7

        DBUtils==2.0.2

# -*- coding: utf-8 -*-
# !/usr/bin/python3
# @Author :luoxun
# @time: 2021/8/18 19:57
# @file: data_warehousing.py
# @Software: PyCharm
import pymysql
from dbutils.pooled_db import PooledDB


db_config = {
    "mincached": 1,
    "maxcached": 4,  # 连接池中最大空闲连接数
    "maxconnections": 5,  #允许的最大连接数
    "blocking": 'True',  # 设置为true,则阻塞并等待直到连接数量减少,false默认情况下将报告错误。
    "ping": 1,  #默认=1表示每当从池中获取时,使用ping()检查连接
    "host": "127.0.0.1",
    "port": 3306,
    "user": "root",
    "passwd": "root",
    "db": "spider",
}

# mysql数据库操作函数
class Operation_mysql(object):
    def __init__(self,db_config):
        self.pool = PooledDB(pymysql, **db_config)  # 创建连接池
        self.conn = self.pool.connection()  # 以后每次需要数据库连接就是用connection()函数获取连接就好了
        self.cursor = self.conn.cursor()
        self.conn.ping(reconnect=True)
    def insert_sql(self,sql):
        try:
            self.cursor.execute(sql)
            self.conn.commit()
            operation_result = '数据插入成功'
        except:
            operation_result = '数据插入失败'
        return operation_result


    def update_sql(self,sql):
        try:
            self.cursor.execute(sql)
            self.conn.commit()
            operation_result = '数据更新成功'
        except:
            operation_result = '数据更新失败'
        return operation_result


    def select_sql(self, sql):
        try:
            self.cursor.execute(sql)
            operation_result = self.cursor.fetchall()
        except:
            operation_result = '数据查询失败'
        return operation_result

    def __del__(self):
        self.cursor.close()

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值