python使用dbutils的PooledDB连接池,操作数据库
1、使用dbutils的PooledDB连接池,操作数据库。
这样就不需要每次执行sql后都关闭数据库连接,频繁的创建连接,消耗时间
2、如果是使用一个连接一直不关闭,多线程下,插入超长字符串到数据库,运行一段时间后很容易出现OperationalError: (2006, ‘MySQL server has gone away’)这个错误。
使用PooledDB解决。
- # coding=utf-8
- """
- 使用DBUtils数据库连接池中的连接,操作数据库
- OperationalError: (2006, ‘MySQL server has gone away’)
- """
- import json
- import pymysql
- import datetime
- from DBUtils.PooledDB import PooledDB
- import pymysql
- class MysqlClient(object):
- __pool = None;
- def __init__(self, mincached=10, maxcached=20, maxshared=10, maxconnections=200, blocking=True,
- maxusage=100, setsession=None, reset=True,
- host='127.0.0.1', port=3306, db='test',
- user='root', passwd='', charset='utf8mb4'):
- """
- :param mincached:连接池中空闲连接的初始数量
- :param maxcached:连接池中空闲连接的最大数量
- :param maxshared:共享连接的最大数量
- :param maxconnections:创建连接池的最大数量
- :param blocking:超过最大连接数量时候的表现,为True等待连接数量下降,为false直接报错处理
- :param maxusage:单个连接的最大重复使用次数
- :param setsession:optional list of SQL commands that may serve to prepare
- the session, e.g. ["set datestyle to ...", "set time zone ..."]
- :param reset:how connections should be reset when returned to the pool
- (False or None to rollback transcations started with begin(),
- True to always issue a rollback for safety's sake)
- :param host:数据库ip地址
- :param port:数据库端口
- :param db:库名
- :param user:用户名
- :param passwd:密码
- :param charset:字符编码
- """
- if not self.__pool:
- self.__class__.__pool = PooledDB(pymysql,
- mincached, maxcached,
- maxshared, maxconnections, blocking,
- maxusage, setsession, reset,
- host=host, port=port, db=db,
- user=user, passwd=passwd,
- charset=charset,
- cursorclass=pymysql.cursors.DictCursor
- )
- self._conn = None
- self._cursor = None
- self.__get_conn()
- def __get_conn(self):
- self._conn = self.__pool.connection();
- self._cursor = self._conn.cursor();
- def close(self):
- try:
- self._cursor.close()
- self._conn.close()
- except Exception as e:
- print e
- def __execute(self, sql, param=()):
- count = self._cursor.execute(sql, param)
- print count
- return count
- @staticmethod
- def __dict_datetime_obj_to_str(result_dict):
- """把字典里面的datatime对象转成字符串,使json转换不出错"""
- if result_dict:
- result_replace = {k: v.__str__() for k, v in result_dict.items() if isinstance(v, datetime.datetime)}
- result_dict.update(result_replace)
- return result_dict
- def select_one(self, sql, param=()):
- """查询单个结果"""
- count = self.__execute(sql, param)
- result = self._cursor.fetchone()
- """:type result:dict"""
- result = self.__dict_datetime_obj_to_str(result)
- return count, result
- def select_many(self, sql, param=()):
- """
- 查询多个结果
- :param sql: qsl语句
- :param param: sql参数
- :return: 结果数量和查询结果集
- """
- count = self.__execute(sql, param)
- result = self._cursor.fetchall()
- """:type result:list"""
- [self.__dict_datetime_obj_to_str(row_dict) for row_dict in result]
- return count, result
- def execute(self, sql, param=()):
- count = self.__execute(sql, param)
- return count
- def begin(self):
- """开启事务"""
- self._conn.autocommit(0)
- def end(self, option='commit'):
- """结束事务"""
- if option == 'commit':
- self._conn.autocommit()
- else:
- self._conn.rollback()
- if __name__ == "__main__":
- mc = MysqlClient()
- sql1 = 'SELECT * FROM shiji WHERE id = 1'
- result1 = mc.select_one(sql1)
- print json.dumps(result1[1], ensure_ascii=False)
- sql2 = 'SELECT * FROM shiji WHERE id IN (%s,%s,%s)'
- param = (2, 3, 4)
- print json.dumps(mc.select_many(sql2, param)[1], ensure_ascii=False)
如果独立使用pymysql数据库,最好是配合DButils库。
上面的用法中是一直使用了mc这个对象,真实意图不是这样的,你可以随意实例化MysqlClient(),用不同的MysqlClient实例操纵数据库。
python使用dbutils的PooledDB连接池,操作数据库的更多相关文章
- 使用python简单连接并操作数据库
python中连接并操作数据库 图示操作流程 一.使用的完整流程 # 1. 导入模块 from pymysql import connect # 2. 创建和数据库服务器的连接,自行设置 服务器地址, ...
- PHP连接MYSQL操作数据库
PHP连接MYSQL操作数据库 <?php $con = mysql_connect("localhost","root",""); ...
- [转载]tornado.database添加PooledDB连接池功能
转载自 http://chenxiaoyu.org/2009/12/01/python-tornado-dbutil.html tornado.database模块简单包装了下对MySQL的操作,短小 ...
- Python3 多线程(连接池)操作MySQL插入数据
1.主要模块DBUtils : 允许在多线程应用和数据库之间连接的模块套件Threading : 提供多线程功能 2.创建连接池PooledDB 基本参数: mincached : 最少的空闲连接数, ...
- 用python自定义实现db2的连接池
想要模仿zabbix的oracle插件orabix来实现对db2的监控,但是Java能力有限,就用python来实现了.但是python常用的连接池PooledDB似乎并不支持db2,一直报这样的错误 ...
- Python的MySQLdb模块安装,连接,操作,增删改
1. 首先确认python的版本为2.3.4以上,如果不是需要升级python的版本 python -V 检查python版本 2. 安装mysql, 比如安装在/usr/local/my ...
- 一种利用ADO连接池操作MySQL的解决方案(VC++)
VC++连接MySQL数据库 常用的方式有三种:ADO.mysql++,mysql API ; 本文只讲述ADO的连接方式. 为什么要使用连接池? 对于简单的数据库应用,完全可以先创建一个常连接(此连 ...
- Java 使用 DBCP mysql 连接池 做数据库操作
需要的jar包有 commons-dbutils , commons-dbcp , commons-pool , mysql-connector-java 本地database.propertties ...
- redis的连接方法|连接池|操作
1.先看下redis的连接 import redis # 连接服务端 r = redis.Redis(host="127.0.0.1",port=6379) #获取所有的key值 ...
随机推荐
- Maven项目编译后classes文件中没有.xml问题
在做spring+mybatiss时,自动扫描都配置正确了,却在运行时出现了如下错误.后来查看target/classes/.../dao/文件夹下,发现只有mapper的class文件,而没有xml ...
- 强大的vim配置文件,让编程更随意
花了很长时间整理的,感觉用起来很方便,共享一下. 我的vim配置主要有以下优点: 1.按F5可以直接编译并执行C.C++.java代码以及执行shell脚本,按“F8”可进行C.C++代码的调试 2. ...
- linux 正则表达式和通配符
linux 正则表达式和通配符 通配符用于查找文件 包含三种: * ? [] * 代表任意个任意字符 ? 代表任意一个字符 [] 代表中括号中的一个字符 正则表达式(正则是包含匹配,只要包含就可以匹 ...
- 百度地图Api进阶教程-点聚合9.html
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...
- WebRTC网关服务器单端口方案实现
标准WebRTC连接建立流程 这里描述的是Trickle ICE过程,并且省略了通话发起与接受的信令部分.流程如下: 1) WebRTC A通过Signal Server转发SDP OFFER到Web ...
- R语言常用基础知识(入门)
data.frame 动态确定列名称 var <- "mpg" #Doesn't work mtcars$var #These both work, but note tha ...
- WinForm窗体继承
在Windows应用程序中,从现有的窗体继承,查看子窗体的设计视图时,会出现错误: 服务容器中已存在服务 System.Windows.Forms.Design.IEventHandlerServic ...
- 3D打印浪潮中的赢家与输家
3D打印浪潮中的赢家与输家 微博 空间 微信 新浪微博 邮箱 QQ好友 人人网 开心网 [导读]虽然目前3D打印行业规模不大且比较分散,但相关上市公司数量惊人.最大的两家是Stratasys和3D S ...
- 【转】【Python】python使用urlopen/urlretrieve下载文件时出现403 forbidden的解决方法
第一:urlopen出现403 #!/usr/bin/env python # -*- coding: utf- -*- import urllib url = "http://www.go ...
- Java Web知识梳理
今天给内部做了个培训,貌似搞错了对象,不该对新人讲这么原理性的东西. anyway,还是放上来吧,不知道有没有人能理清其中的逻辑 ^ _ ^ 问题:为什么要用tomcattomcat: servlet ...