1、使用dbutils的PooledDB连接池,操作数据库。

这样就不需要每次执行sql后都关闭数据库连接,频繁的创建连接,消耗时间

2、如果是使用一个连接一直不关闭,多线程下,插入超长字符串到数据库,运行一段时间后很容易出现OperationalError: (2006, ‘MySQL server has gone away’)这个错误。

使用PooledDB解决。

  1. # coding=utf-8
  2. """
  3. 使用DBUtils数据库连接池中的连接,操作数据库
  4. OperationalError: (2006, ‘MySQL server has gone away’)
  5. """
  6. import json
  7. import pymysql
  8. import datetime
  9. from DBUtils.PooledDB import PooledDB
  10. import pymysql
  11.  
  12. class MysqlClient(object):
  13. __pool = None;
  14.  
  15. def __init__(self, mincached=10, maxcached=20, maxshared=10, maxconnections=200, blocking=True,
  16. maxusage=100, setsession=None, reset=True,
  17. host='127.0.0.1', port=3306, db='test',
  18. user='root', passwd='', charset='utf8mb4'):
  19. """
  20.  
  21. :param mincached:连接池中空闲连接的初始数量
  22. :param maxcached:连接池中空闲连接的最大数量
  23. :param maxshared:共享连接的最大数量
  24. :param maxconnections:创建连接池的最大数量
  25. :param blocking:超过最大连接数量时候的表现,为True等待连接数量下降,为false直接报错处理
  26. :param maxusage:单个连接的最大重复使用次数
  27. :param setsession:optional list of SQL commands that may serve to prepare
  28. the session, e.g. ["set datestyle to ...", "set time zone ..."]
  29. :param reset:how connections should be reset when returned to the pool
  30. (False or None to rollback transcations started with begin(),
  31. True to always issue a rollback for safety's sake)
  32. :param host:数据库ip地址
  33. :param port:数据库端口
  34. :param db:库名
  35. :param user:用户名
  36. :param passwd:密码
  37. :param charset:字符编码
  38. """
  39.  
  40. if not self.__pool:
  41. self.__class__.__pool = PooledDB(pymysql,
  42. mincached, maxcached,
  43. maxshared, maxconnections, blocking,
  44. maxusage, setsession, reset,
  45. host=host, port=port, db=db,
  46. user=user, passwd=passwd,
  47. charset=charset,
  48. cursorclass=pymysql.cursors.DictCursor
  49. )
  50. self._conn = None
  51. self._cursor = None
  52. self.__get_conn()
  53.  
  54. def __get_conn(self):
  55. self._conn = self.__pool.connection();
  56. self._cursor = self._conn.cursor();
  57.  
  58. def close(self):
  59. try:
  60. self._cursor.close()
  61. self._conn.close()
  62. except Exception as e:
  63. print e
  64.  
  65. def __execute(self, sql, param=()):
  66. count = self._cursor.execute(sql, param)
  67. print count
  68. return count
  69.  
  70. @staticmethod
  71. def __dict_datetime_obj_to_str(result_dict):
  72. """把字典里面的datatime对象转成字符串,使json转换不出错"""
  73. if result_dict:
  74. result_replace = {k: v.__str__() for k, v in result_dict.items() if isinstance(v, datetime.datetime)}
  75. result_dict.update(result_replace)
  76. return result_dict
  77.  
  78. def select_one(self, sql, param=()):
  79. """查询单个结果"""
  80. count = self.__execute(sql, param)
  81. result = self._cursor.fetchone()
  82. """:type result:dict"""
  83. result = self.__dict_datetime_obj_to_str(result)
  84. return count, result
  85.  
  86. def select_many(self, sql, param=()):
  87. """
  88. 查询多个结果
  89. :param sql: qsl语句
  90. :param param: sql参数
  91. :return: 结果数量和查询结果集
  92. """
  93. count = self.__execute(sql, param)
  94. result = self._cursor.fetchall()
  95. """:type result:list"""
  96. [self.__dict_datetime_obj_to_str(row_dict) for row_dict in result]
  97. return count, result
  98.  
  99. def execute(self, sql, param=()):
  100. count = self.__execute(sql, param)
  101. return count
  102.  
  103. def begin(self):
  104. """开启事务"""
  105. self._conn.autocommit(0)
  106.  
  107. def end(self, option='commit'):
  108. """结束事务"""
  109. if option == 'commit':
  110. self._conn.autocommit()
  111. else:
  112. self._conn.rollback()
  113.  
  114. if __name__ == "__main__":
  115. mc = MysqlClient()
  116. sql1 = 'SELECT * FROM shiji WHERE id = 1'
  117. result1 = mc.select_one(sql1)
  118. print json.dumps(result1[1], ensure_ascii=False)
  119.  
  120. sql2 = 'SELECT * FROM shiji WHERE id IN (%s,%s,%s)'
  121. param = (2, 3, 4)
  122. 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. Maven项目编译后classes文件中没有.xml问题

    在做spring+mybatiss时,自动扫描都配置正确了,却在运行时出现了如下错误.后来查看target/classes/.../dao/文件夹下,发现只有mapper的class文件,而没有xml ...

  2. 强大的vim配置文件,让编程更随意

    花了很长时间整理的,感觉用起来很方便,共享一下. 我的vim配置主要有以下优点: 1.按F5可以直接编译并执行C.C++.java代码以及执行shell脚本,按“F8”可进行C.C++代码的调试 2. ...

  3. linux 正则表达式和通配符

    linux 正则表达式和通配符 通配符用于查找文件 包含三种:  * ? [] * 代表任意个任意字符 ? 代表任意一个字符 [] 代表中括号中的一个字符 正则表达式(正则是包含匹配,只要包含就可以匹 ...

  4. 百度地图Api进阶教程-点聚合9.html

    <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...

  5. WebRTC网关服务器单端口方案实现

    标准WebRTC连接建立流程 这里描述的是Trickle ICE过程,并且省略了通话发起与接受的信令部分.流程如下: 1) WebRTC A通过Signal Server转发SDP OFFER到Web ...

  6. R语言常用基础知识(入门)

    data.frame 动态确定列名称 var <- "mpg" #Doesn't work mtcars$var #These both work, but note tha ...

  7. WinForm窗体继承

    在Windows应用程序中,从现有的窗体继承,查看子窗体的设计视图时,会出现错误: 服务容器中已存在服务 System.Windows.Forms.Design.IEventHandlerServic ...

  8. 3D打印浪潮中的赢家与输家

    3D打印浪潮中的赢家与输家 微博 空间 微信 新浪微博 邮箱 QQ好友 人人网 开心网 [导读]虽然目前3D打印行业规模不大且比较分散,但相关上市公司数量惊人.最大的两家是Stratasys和3D S ...

  9. 【转】【Python】python使用urlopen/urlretrieve下载文件时出现403 forbidden的解决方法

    第一:urlopen出现403 #!/usr/bin/env python # -*- coding: utf- -*- import urllib url = "http://www.go ...

  10. Java Web知识梳理

    今天给内部做了个培训,貌似搞错了对象,不该对新人讲这么原理性的东西. anyway,还是放上来吧,不知道有没有人能理清其中的逻辑 ^ _ ^ 问题:为什么要用tomcattomcat: servlet ...