原文链接:http://www.danfengcao.info/python/2015/12/26/lightweight-python-mysql-class.html

mysqldb是Python操作MySQL数据库的一个常用包。但在使用过程中,我认为用起来还不够简便。为此,我在mysqldb的基础上封装了一个Python类LightMysql。

先来看如何使用

example.py

#!/usr/bin/env python
# -*- coding: utf-8 -*- from LightMysql import LightMysql if __name__ == '__main__': # 配置信息,其中host, port, user, passwd, db为必需
dbconfig = {'host':'127.0.0.1',
'port': 3306,
'user':'danfengcao',
'passwd':'',
'db':'test',
'charset':'utf8'} db = LightMysql(dbconfig) # 创建LightMysql对象,若连接超时,会自动重连 # 查找(select, show)都使用query()函数
sql_select = "SELECT * FROM Customer"
result_all = db.query(sql_select) # 返回全部数据
result_count = db.query(sql_select, 'count') # 返回有多少行
result_one = db.query(sql_select, 'one') # 返回一行 # 增删改都使用dml()函数
sql_update = "update Customer set Cost=2 where Id=2"
result_update = db.dml(sql_update)
sql_delete = "delete from Customer where Id=2"
result_delete = db.dml(sql_delete) db.close() # 操作结束,关闭对象
使用前需安装

该类依赖于MySQLdb,故需先安装MySQLdb包。

  • 使用python包管理器(easy_install或pip)安装

easy_install mysql-python 或 pip install MySQL-python

  • 或者手动编译安装

http://mysql-python.sourceforge.net/

LightMysql完整代码

#!/usr/bin/env python
# -*- coding: utf-8 -*- import MySQLdb
import time, re class LightMysql:
"""Lightweight python class connects to MySQL. """ _dbconfig = None
_cursor = None
_connect = None
_error_code = '' # error_code from MySQLdb TIMEOUT_DEADLINE = 30 # quit connect if beyond 30S
TIMEOUT_THREAD = 10 # threadhold of one connect
TIMEOUT_TOTAL = 0 # total time the connects have waste def __init__(self, dbconfig): try:
self._dbconfig = dbconfig
self.dbconfig_test(dbconfig)
self._connect = MySQLdb.connect(
host=self._dbconfig['host'],
port=self._dbconfig['port'],
user=self._dbconfig['user'],
passwd=self._dbconfig['passwd'],
db=self._dbconfig['db'],
charset=self._dbconfig['charset'],
connect_timeout=self.TIMEOUT_THREAD)
except MySQLdb.Error, e:
self._error_code = e.args[0]
error_msg = "%s --- %s" % (time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), type(e).__name__), e.args[0], e.args[1]
print error_msg # reconnect if not reach TIMEOUT_DEADLINE.
if self.TIMEOUT_TOTAL < self.TIMEOUT_DEADLINE:
interval = 0
self.TIMEOUT_TOTAL += (interval + self.TIMEOUT_THREAD)
time.sleep(interval)
return self.__init__(dbconfig)
raise Exception(error_msg) self._cursor = self._connect.cursor(MySQLdb.cursors.DictCursor) def dbconfig_test(self, dbconfig):
flag = True
if type(dbconfig) is not dict:
print 'dbconfig is not dict'
flag = False
else:
for key in ['host','port','user','passwd','db']:
if not dbconfig.has_key(key):
print "dbconfig error: do not have %s" % key
flag = False
if not dbconfig.has_key('charset'):
self._dbconfig['charset'] = 'utf8' if not flag:
raise Exception('Dbconfig Error')
return flag def query(self, sql, ret_type='all'):
try:
self._cursor.execute("SET NAMES utf8")
self._cursor.execute(sql)
if ret_type == 'all':
return self.rows2array(self._cursor.fetchall())
elif ret_type == 'one':
return self._cursor.fetchone()
elif ret_type == 'count':
return self._cursor.rowcount
except MySQLdb.Error, e:
self._error_code = e.args[0]
print "Mysql execute error:",e.args[0],e.args[1]
return False def dml(self, sql):
'''update or delete or insert'''
try:
self._cursor.execute("SET NAMES utf8")
self._cursor.execute(sql)
self._connect.commit()
type = self.dml_type(sql)
# if primary key is auto increase, return inserted ID.
if type == 'insert':
return self._connect.insert_id()
else:
return True
except MySQLdb.Error, e:
self._error_code = e.args[0]
print "Mysql execute error:",e.args[0],e.args[1]
return False def dml_type(self, sql):
re_dml = re.compile('^(?P<dml>\w+)\s+', re.I)
m = re_dml.match(sql)
if m:
if m.group("dml").lower() == 'delete':
return 'delete'
elif m.group("dml").lower() == 'update':
return 'update'
elif m.group("dml").lower() == 'insert':
return 'insert'
print "%s --- Warning: '%s' is not dml." % (time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), sql)
return False def rows2array(self, data):
'''transfer tuple to array.'''
result = []
for da in data:
if type(da) is not dict:
raise Exception('Format Error: data is not a dict.')
result.append(da)
return result def __del__(self):
'''free source.'''
try:
self._cursor.close()
self._connect.close()
except:
pass def close(self):
self.__del__()
 

克隆LightMysql代码

Reference
  1. 教为学:MySQLdb的几种安装方式
  2. MySQL-Python documentation
  3. fkook python_mysql

LightMysql:为方便操作MySQL而封装的Python类的更多相关文章

  1. php操作Mysql 以及封装常用的函数 用外连接连接3个表的案例

    <?php header("content-type;text/html;charset=utf-8"); //数据库连接define('DB_HOST','localhos ...

  2. C#连接操作MySQL数据库详细步骤 帮助类等(二次改进版)

    最近准备写一个仓库管理的项目 客户要求使用C#编写MySQL存储数据 为了方便,整理了数据库操作的工具类 首先在项目App.config 文件下添加节点 <connectionStrings&g ...

  3. python中操作excel数据 封装成一个类

    本文用python中openpyxl库,封装成excel数据的读写方法 from openpyxl import load_workbook from openpyxl.worksheet.works ...

  4. paramiko操作详解(封装好的类,可以直接使用)

    #!/usr/bin/env python #encoding:utf8 #author: djoker import paramiko class myParamiko: def __init__( ...

  5. jdbc操作mysql

    本文讲述2点: 一. jdbc 操作 MySQL .(封装一个JdbcUtils.java类,实现数据库表的增删改查) 1. 建立数据库连接 Class.forName(DRIVER); connec ...

  6. python3操作MySQL数据库

    安装PyMySQL 下载地址:https://pypi.python.org/pypi/PyMySQL 1.把操作Mysql数据库封装成类,数据库和表先建好 import pymysql.cursor ...

  7. python 操作 mysql基础补充

    前言 本篇的主要内容为整理mysql的基础内容,分享的同时方便日后查阅,同时结合python的学习整理python操作mysql的方法以及python的ORM. 一.数据库初探 在开始mysql之前先 ...

  8. (转)Python中操作mysql的pymysql模块详解

    原文:https://www.cnblogs.com/wt11/p/6141225.html https://shockerli.net/post/python3-pymysql/----Python ...

  9. python操作mysql基础一

    python操作mysql基础一 使用Python操作MySQL的一些基本方法 前奏 为了能操作数据库, 首先我们要有一个数据库, 所以要首先安装Mysql, 然后创建一个测试数据库python_te ...

随机推荐

  1. 通过手动创建统计信息优化sql查询性能案例

    本质原因在于:SQL Server 统计信息只包含复合索引的第一个列的信息,而不包含复合索引数据组合的信息 来源于工作中的一个实际问题, 这里是组合列数据不均匀导致查询无法预估数据行数,从而导致无法选 ...

  2. Halcon11与VS2010联合开发

    刚开始学习Halcon,需要使用Halcon与C++联合开发软件,查了网上的资料都是Halcon10的,我用的是Halcon11和VS2010的开发环境,实践了一下发现有一些问题,于是把自己的配置的过 ...

  3. TeamCity : 安装 Server

    本文介绍在 Ubuntu Server 14.04 中安装 TeamCity Server 10.0.1.Ubuntu Server 上已经创建了用户  tcuser.TeamCity 的安装包为 T ...

  4. jQuery动画

    一.显示和隐藏 hide().show() 1.show():显示被选的元素 2.hide():隐藏被选的元素 3.toggle():对被选元素进行隐藏和显示的切换 语法: $(selector).h ...

  5. 在PHP语言中使用JSON和将json还原成数组

    在之前我写过php返回json数据简单实例,刚刚上网,突然发现一篇文章,也是介绍json的,还挺详细,值得参考.内容如下 从5.2版本开始,PHP原生提供json_encode()和json_deco ...

  6. UDS(ISO14229-2006) 汉译(No.7 应用层协议)【未完,待续】

    7.1定义 应用层协议通常作为确认消息的传输,意味着从客户端发送的每一个请求都将有由服务器端产生的与之相对的响应. 唯一的例外在于:例如使用了功能寻址方式,或者该请求/指示没有指定生成响应/确定的少数 ...

  7. Java编程里类的继承

    今天,我们将要讨论的内容是Java里面类的继承的相关概念. 说到继承,我相信大家都不陌生.生活中,子承父业,子女继承父母的财产,这就是继承.实际上,Java里的继承也是如此.对于一个类来说,它的数据成 ...

  8. 19、ASP.NET MVC入门到精通——Unity

    一.IOC介绍 IOC(Inversion of Control),中文译为控制反转,又称为“依赖注入”(DI =Dependence Injection) IOC的基本概念是:不创建对象,但是描述创 ...

  9. 字符编码笔记:ASCII,Unicode和UTF-8

    很久很久以前,有一群人,他们决定用8个可以开合的晶体管来组合成不同的状态,以表示世界上的万物.他们看到8个开关状态是好的,于是他们把这称为"字节". 再后来,他们又做了一些可以处理 ...

  10. [C/C++] DebugBreak

    在代码中直接调用DebugBreak()函数,可以使程序中断运行,和在IDE中设置断点中断运行的道理是一样的. 用这种方式,一些情况下比打断点更方便调试,如下,在test()函数返回0时激活断点 #i ...