LightMysql:为方便操作MySQL而封装的Python类
原文链接: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
- 或者手动编译安装
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__()
Reference
LightMysql:为方便操作MySQL而封装的Python类的更多相关文章
- php操作Mysql 以及封装常用的函数 用外连接连接3个表的案例
<?php header("content-type;text/html;charset=utf-8"); //数据库连接define('DB_HOST','localhos ...
- C#连接操作MySQL数据库详细步骤 帮助类等(二次改进版)
最近准备写一个仓库管理的项目 客户要求使用C#编写MySQL存储数据 为了方便,整理了数据库操作的工具类 首先在项目App.config 文件下添加节点 <connectionStrings&g ...
- python中操作excel数据 封装成一个类
本文用python中openpyxl库,封装成excel数据的读写方法 from openpyxl import load_workbook from openpyxl.worksheet.works ...
- paramiko操作详解(封装好的类,可以直接使用)
#!/usr/bin/env python #encoding:utf8 #author: djoker import paramiko class myParamiko: def __init__( ...
- jdbc操作mysql
本文讲述2点: 一. jdbc 操作 MySQL .(封装一个JdbcUtils.java类,实现数据库表的增删改查) 1. 建立数据库连接 Class.forName(DRIVER); connec ...
- python3操作MySQL数据库
安装PyMySQL 下载地址:https://pypi.python.org/pypi/PyMySQL 1.把操作Mysql数据库封装成类,数据库和表先建好 import pymysql.cursor ...
- python 操作 mysql基础补充
前言 本篇的主要内容为整理mysql的基础内容,分享的同时方便日后查阅,同时结合python的学习整理python操作mysql的方法以及python的ORM. 一.数据库初探 在开始mysql之前先 ...
- (转)Python中操作mysql的pymysql模块详解
原文:https://www.cnblogs.com/wt11/p/6141225.html https://shockerli.net/post/python3-pymysql/----Python ...
- python操作mysql基础一
python操作mysql基础一 使用Python操作MySQL的一些基本方法 前奏 为了能操作数据库, 首先我们要有一个数据库, 所以要首先安装Mysql, 然后创建一个测试数据库python_te ...
随机推荐
- 【JAVA】基于MVC架构Java技术荟萃案例演练
基于JAVA-MVC技术的顾客管理项目案例总结 作者 白宁超 2016年6月9日22:47:08 阅读前瞻:本文源于对javaweb相关技术和资料汇总,涉及大量javaweb基础技术诸如:Servle ...
- Hadoop入门学习笔记---part2
在<Hadoop入门学习笔记---part1>中感觉自己虽然总结的比较详细,但是始终感觉有点凌乱.不够系统化,不够简洁.经过自己的推敲和总结,现在在此处概括性的总结一下,认为在准备搭建ha ...
- OpenCV2:Mat属性type,depth,step
在OpenCV2中Mat类无疑使占据着核心地位的,前段时间初学OpenCV2时对Mat类有了个初步的了解,见OpenCV2:Mat初学.这几天试着用OpenCV2实现了图像缩小的两种算法:基于等间隔采 ...
- 【非原创】IOS 验证文字是否是中文
从环信中找到的部分不错的代码,拿出来记录一下 是否是中文 -(BOOL)isChinese{ NSString *match=@"(^[\u4e00-\u9fa5]+$)"; NS ...
- Xamarin.Android之Splash的几种简单实现
对现在的APP软件来说,基本上都会有一个Splash页面,类似大家常说的欢迎页面.启动界面之类的. 正常来说这个页面都会有一些相关的信息,比如一些理念,Logo,版本信息等 下面就来看看在Xamari ...
- Asp.net 面向接口可扩展框架之消息队列组件
消息队列对大多数人应该比较陌生.但是要提到MQ听说过的人会多很多.MQ就是英文单词"Message queue"的缩写,翻译成中文就是消息队列(我英语差,翻译错了请告知). PS: ...
- Unity3D 5.x 简单实例 - 脚本编写
1,Vector3 类型变量存储向量坐标值 Vector3.forward Vector3(0,0,1) Vector3.up Vector3(0,1,0) Vector3.right Vector3 ...
- oracle触发器详解
触发器是许多关系数据库系统都提供的一项技术.在ORACLE系统里,触发器类似过程和函数,都有声明,执行和异常处理过程的PL/SQL块. 1.触发器类型 触发器在数据库里以独立的对象存储,它与存储过程和 ...
- input输入框提示语
<input id="username" name="username" type="text" placeholder=" ...
- spring入门(三)【事务控制】
在开发中需要操作数据库,进行增.删.改操作的过程中属于一次操作,如果在一个业务中需要更新多张表,那么任意一张表的更新失败,整个业务的更新就是失败,这时那些更新成功的表必须回滚,否则业务会出错,这时就要 ...