配置文件:
操作源码:
# -*- coding:utf-8 -*-
import pymysql,os,configparser
from DBUtils.PooledDB import PooledDB
class Config(object):
# 读取配置文件
def __init__(self, config_filename = "db.ini"):
filepath = os.path.join(os.path.dirname(__file__), config_filename)
self.cf = configparser.ConfigParser()
self.cf.read(filepath)
def get_sections(self):
return self.cf.sections()
def get_options(self,section):
return self.cf.options(section)
def get_content(self,section):
result = {}
for option in self.get_options(section):
value = self.cf.get(section, option)
result[option] = int(value) if value.isdigit() else value
return result
class BasePymysqlPool(object):
def __init__(self, host, port, user, password, db_name=None):
self.host = host
self.port = int(port)
self.user = user
self.password = str(password)
self.db_name = db_name
self.conn = None
self.cursor = None
class MyPymysqlPool(BasePymysqlPool):
"""
MYSQL数据库对象,负责产生数据库连接 , 此类中的连接采用连接池实现获取连接对象:conn = Mysql.getConn()
释放连接对象;conn.close()或del conn
"""
# 连接池对象
__pool = None # 私有成员
def __init__(self, conf_name=None):
# 读取连接数据库的配置
self.conf = Config().get_content(conf_name) # 读取配置文件
print(self.conf)
super(MyPymysqlPool, self).__init__(**self.conf) # 将读取结果初始化
# 数据库构造函数,从连接池中取出连接,并生成操作游标
self._conn = self.__getConn() # 类成员,打开数据库连接
self._cursor = self._conn.cursor() # 类成员,获取游标
def __getConn(self):
"""
@summary: 静态方法,从连接池中取出连接
@return MySQLdb.connection
@这里具体连接数根据机器配置来自定义
"""
if MyPymysqlPool.__pool is None:
__pool = PooledDB(creator = pymysql,
mincached = 1,
maxcached = 20,
host = self.host,
port = self.port,
user = self.user,
password = self.password,
db = self.db_name,
charset = 'utf8'
)
return __pool.connection()
def select(self, sql, param=None):
"""
@summary: 执行查询,并取出所有结果集
@param sql:查询SQL,如果有查询条件,请只指定条件列表,并将条件值使用参数[param]传递进来
@param param: 可选参数,条件列表值(元组/列表)
@return: result list(字典对象)/boolean 查询到的结果集
"""
if param is None:
count = self._cursor.execute(sql)
else:
count = self._cursor.execute(sql, param)
if count> 0:
result = self._cursor.fetchall()
else:
result = False
return result
def edit(self, sql, param=None):
if param is None:
count = self._cursor.execute(sql)
else:
count = self._cursor.execute(sql, param)
self._conn.commit()
if count < 0:
self._conn.rollback()
count = False
return count
def begin(self):
self._conn.autocommit(0)
def end(self, option='commit'):
if option == 'commint':
self._conn.commit()
else:
self._conn.rollback()
def dispose(self, isEnd=1):
if isEnd == 1:
self.end('commit')
else:
self.end('rollback')
self._cursor.close()
self._conn.close()
test程序:
from log_analysis.dbpool import MyPymysqlPool
sql = MyPymysqlPool('mysql')
s = "SELECT * FROM dealwitht ;"
result = sql.select(s)
print(result)
t = """INSERT INTO dealwitht (pro_time, error_status)VALUES (777777, "0"); """
ints = sql.edit(t)
print(ints)
sql.dispose()
测试结果:
{'host': '10.18.6.105', 'db_name': 'vicky', 'user': 'yzplatform', 'password': 'yzplatform', 'port': 3306}
((1, 1111, '0'), (5, 1111, '0'), (7, 1111, '0'), (8, 1111, '0'), (12, 1111, '0'), (16, 12221, '0'), (21, 22222, '0'), (22, 666666, '0'), (23, 666666, '0'), (24, 666666, '0'), (25, 666666, '0'), (26, 666666, '0'), (27, 666666, '0'))
1