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连接池,操作数据库的更多相关文章

  1. 使用python简单连接并操作数据库

    python中连接并操作数据库 图示操作流程 一.使用的完整流程 # 1. 导入模块 from pymysql import connect # 2. 创建和数据库服务器的连接,自行设置 服务器地址, ...

  2. PHP连接MYSQL操作数据库

    PHP连接MYSQL操作数据库 <?php $con = mysql_connect("localhost","root",""); ...

  3. [转载]tornado.database添加PooledDB连接池功能

    转载自 http://chenxiaoyu.org/2009/12/01/python-tornado-dbutil.html tornado.database模块简单包装了下对MySQL的操作,短小 ...

  4. Python3 多线程(连接池)操作MySQL插入数据

    1.主要模块DBUtils : 允许在多线程应用和数据库之间连接的模块套件Threading : 提供多线程功能 2.创建连接池PooledDB 基本参数: mincached : 最少的空闲连接数, ...

  5. 用python自定义实现db2的连接池

    想要模仿zabbix的oracle插件orabix来实现对db2的监控,但是Java能力有限,就用python来实现了.但是python常用的连接池PooledDB似乎并不支持db2,一直报这样的错误 ...

  6. Python的MySQLdb模块安装,连接,操作,增删改

    1. 首先确认python的版本为2.3.4以上,如果不是需要升级python的版本     python -V   检查python版本 2. 安装mysql, 比如安装在/usr/local/my ...

  7. 一种利用ADO连接池操作MySQL的解决方案(VC++)

    VC++连接MySQL数据库 常用的方式有三种:ADO.mysql++,mysql API ; 本文只讲述ADO的连接方式. 为什么要使用连接池? 对于简单的数据库应用,完全可以先创建一个常连接(此连 ...

  8. Java 使用 DBCP mysql 连接池 做数据库操作

    需要的jar包有 commons-dbutils , commons-dbcp , commons-pool , mysql-connector-java 本地database.propertties ...

  9. redis的连接方法|连接池|操作

    1.先看下redis的连接 import redis # 连接服务端 r = redis.Redis(host="127.0.0.1",port=6379) #获取所有的key值 ...

随机推荐

  1. vba的一个File操作类

    Option Explicit '-------------------------------------------------------- '[Class name]: clsTxtFile ...

  2. android开发(33) 让 actionbar 透明2

    让 actionbar 的背景 透明 我需要一个 透明的actionbar ,找到如下方法实现: 1. 首先,设置ActionBar 浮动到主界面上来. 2. 然后,设置ActionBar的背景色,透 ...

  3. iOS开发小技巧 - runtime适配字体

    iOS开发小技巧 - runtime适配字体 版权声明:本文为博主原创文章,未经博主允许不得转载,有问题可联系博主Email: liuyongjiesail@icloud.com 一个iOS开发项目无 ...

  4. spring boot 使用拦截器 无法注入 配置值 、bean问题

    参考:https://www.cnblogs.com/SimonHu1993/p/8360701.html 一定要将 拦截器组件 交给spring容器进行管理,这样才能注入配置值,或者注入bean: ...

  5. Reservoir Sampling - 蓄水池抽样问题

    问题起源于编程珠玑Column 12中的题目10,其描述如下: How could you select one of n objects at random, where you see the o ...

  6. SQL server 分页方法小结

    这里面介绍一下常用的分页方法: 1.使用top来分页 select top @pageSize * from table where id not in (select top @pageSize*( ...

  7. 巧用style的另类写法

    看到style,不少人可能会说这个我知道,就是控件写属性的话可以通过style来实现代码的复用,单独把这些属性及其参数写成style就可以便捷的调用. <?xml version="1 ...

  8. ps常用快捷键

    一. 二. 三.

  9. GENA

    GENA这是事件消息采用格式,是所谓“普通事件通知体系Generic Event Notification Architecture”的缩写

  10. Google ProtocolBuffers2.4.1应用说明(一)

    1.概念 Protocol buffers是一个用来序列化结构化数据的技术,支持多种语言诸如C++.Java以及Python语言,可以使用该技术来持久化数据或者序列化成网络传输的数据.相比较一些其他的 ...