环境:
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()