# Filename:mysql_class.py
# Author:Rain.Zen; Date: 2014-04-15 import MySQLdb class MyDb: '''初始化[类似于构造函数]'''
def __init__(self, host, user, password, charset = 'utf8'):
self.host = host
self.user = user
self.password = password
self.charset = charset
try:
self.conn = MySQLdb.connect(host = self.host, user = self.user, passwd = self.password, charset = self.charset)
self.cur = self.conn.cursor()
except MySQLdb.Error as e:
print('MySQL Error %d: %s' % (e.args[0], e.args[1])) '''组合字符串'''
def joinData(self, data, char = ','):
return char.join(data) '''解析条件语句,参数类型[{dict}, 'AND|OR'] | {dict}'''
def parseMap(self, condition) :
if isinstance(condition, list) :
dictMap = condition[0]
logic = ' '+ condition[1] +' '
else :
dictMap = condition
logic = ' AND ' if isinstance(dictMap, dict) :
for k, v in dictMap.items():
dictMap[k] = "`"+ k +"` = '"+ str(v) +"'"
return self.joinData(dictMap.values(), logic)
else :
return '1 = 1' '''选择数据表'''
def selectDb(self, db):
try :
self.conn.select_db(db)
except MySQLdb.Error as e:
print('MySQL Error %d: %s' % (e.args[0], e.args[1])) '''执行SQL语句'''
def query(self, sql):
try :
return self.cur.execute(sql)
except MySQLdb.Error as e:
print 'MySQL Error: %s \nSQL: %s' % (e, sql) '''添加一条信息'''
def addOne(self, table, dictData):
for field, value in dictData.items():
dictData[field] = "'"+ str(value) +"'"
self.query('INSERT INTO ' + table + "("+ self.joinData(dictData.keys()) +') VALUES('+ self.joinData(dictData.values()) +')')
return self.cur.lastrowid '''修改一条信息[根据条件]'''
def saveOne(self, table, dictData, condition):
for key, val in dictData.items():
dictData[key] = "`"+ key +"` = '"+ str(val) +"'"
save_sql = 'UPDATE ' + table + ' SET ' + self.joinData(dictData.values()) + ' WHERE ' + self.parseMap(condition)
return self.query(save_sql) '''删除信息[根据条件]'''
def deleteOne(self, table, condition):
return self.query('DELETE FROM ' + table + ' WHERE ' + self.parseMap(condition)) '''读取单条信息[根据条件]'''
def fetchOne(self, tabel, condition, fields = '*', dataType = 0):
field = isinstance(fields, list) and self.joinData(fields) or fields
self.query('SELECT '+ field +' FROM ' + tabel + ' WHERE ' + self.parseMap(condition))
tupleData = self.cur.fetchone()
if dataType == 0 or fields == '*' :
return tupleData
else :
dictData = {}
n = 0
for k in fields:
dictData[k] = tupleData[n]
n = n + 1
return dictData '''读取多条信息[根据条件]'''
def fetchSome(self, tabel, condition, fields = '*', dataType = 0):
field = isinstance(fields, list) and self.joinData(fields) or fields
self.query('SELECT '+ field +' FROM ' + tabel + ' WHERE ' + self.parseMap(condition))
tupleData = self.cur.fetchall()
count = self.cur.rowcount
if count > 0:
if dataType == 0 or fields == '*' :
return (int(count), tupleData)
else :
listData = []
for row in tupleData:
dictData = {}
n = 0
for k in fields:
dictData[k] = row[n]
n = n + 1
listData.append(dictData)
return (int(count), listData)
else:
return False '''获取信息总数[根据条件]'''
def getCount(self, tabel, condition = 0):
where = isinstance(condition, dict) and ' WHERE ' + self.parseMap(condition) or ''
self.query('SELECT 0 FROM ' + tabel + where)
return self.cur.rowcount '''提交事务'''
def commit(self):
self.conn.commit() '''关闭句柄和连接'''
def close(self):
self.cur.close()
self.conn.close()

DEMO

 # Filename: test_mysql.py

 from mysql_class import MyDb

 '''测试开始'''

 '''连接数据库[实例化]'''
my_db = MyDb('127.0.0.1', 'python_user', '') '''选择数据库'''
my_db.selectDb('test') '''修改单条信息
dictData = {'class' : 'DD', 'name' : 'Pitt.C', 'subject' : 'Match_01', 'score' : 60}
condition = [{'class' : 'DD', 'name' : 'Tom'}, 'OR']
print my_db.saveOne('cla_info', dictData, condition)''' '''删除信息
condition = [{'class':'DD', 'name':'bd', 'id':17}, 'OR']
print my_db.deleteOne('cla_info', condition)''' '''获取单条信息
fields = ['class', 'name', 'subject', 'score', 'comment']
condition = {'id':6}
print my_db.fetchOne('cla_info', condition, fields)''' '''新增[单条]
dictData = {'class' : 'DDD', 'name' : 'Pitt', 'subject' : 'Match', 'score' : 97}
in_id = my_db.addOne('cla_info', dictData)
print 'Successful add data: ID(%d)' % in_id''' '''查询数据
field = ['class', 'name', 'subject', 'score', 'comment']
condition = {'name':'小明'}
ary = my_db.fetchSome('cla_info', condition, field, 1)
if ary or False :
print 'The total is:',ary[0]
print ary[1]''' '''获取总数
condition = {'name':'小明'}
print my_db.getCount('cla_info')''' '''事务处理'''
my_db.commit() '''关闭句柄和连接'''
my_db.close()

Python封装的访问MySQL数据库的类及DEMO的更多相关文章

  1. 【python小记】访问mysql数据库

    题记: 最近因为工作需要,学习了python,瞬间对这个轻松快捷的语给吸引了,以前只知道js脚本是写网页的,没有想到python这个脚本语言的应用范围可以这么广泛,现在做一些简单或稍微复杂的操作,基本 ...

  2. C#访问MySQL数据库帮助类

    MySQL数据库访问帮助类 1.项目添加引用官方MySQL动态库MySql.Data.dll 下载地址:MySql.Data.dll(也可以到官网下载动态库)项目添加引用 这里有一个Mysql帮助类的 ...

  3. Python访问MySQL数据库并实现其增删改查功能

    概述:对于访问MySQL数据库的操作,我想大家也都有一些了解.不过,因为最近在学习Python,以下就用Python来实现它.其中包括创建数据库和数据表.插入记录.删除记录.修改记录数据.查询数据.删 ...

  4. 在Eclipse中使用JDBC访问MySQL数据库的配置方法

    在Eclipse中使用JDBC访问MySQL数据库的配置方法 分类: DATABASE 数据结构与算法2009-10-10 16:37 5313人阅读 评论(10) 收藏 举报 jdbcmysql数据 ...

  5. 封装好的MySQL.class.php类

    封装好的MySQL.class.php类 作用:数据库操作类 <?php header('content-type:text/html;charset=utf-8'); class MySQLD ...

  6. PHP访问MySql数据库介绍

    在网站后台,经常要与数据库打交道.本文介绍如何使用XAMPP来管理MySql数据库及如何用PHP来访问MySql数据库. 一.使用XAMPP来管理MySql数据库 首先使用XAMPP打开MySql的管 ...

  7. C#连接、访问MySQL数据库

    一.准备工具 visual stuido(本示例使用visual studio 2010) MySql.Data.dll mysql_installer_community_V5.6.21.1_set ...

  8. C#访问MySQL数据库(winform+EF)

    原文:C#访问MySQL数据库(winform+EF) 以前都是C#连接SQLServer,现在MySQL也比较火了,而且是开源跨平台的,这里连接使用一下,主要是体会一下整个流程,这里使用的是winf ...

  9. Spring Boot入门(六):使用MyBatis访问MySql数据库(注解方式)

    本系列博客记录自己学习Spring Boot的历程,如帮助到你,不胜荣幸,如有错误,欢迎指正! 本篇博客我们讲解下在Spring Boot中使用MyBatis访问MySql数据库的简单用法. 1.前期 ...

随机推荐

  1. MVC零基础学习整理(一)

    1.Mvc程序的启动页的设置:修改程序的Global.asax文件

  2. 编译安装apache2.4

    一.编译安装apache2.4Apache官方说:与Apache 2.2.x相比,Apache 2.4.x提供了很多性能方面的提升,包括支持更大流量.更好地支持云计算.利用更少的内存处理更多的并发等. ...

  3. 转载:MyEclipse启动Tomcat缓慢的原因及解决办法

    转自linux公社 不知道朋友们是否有一种烦恼:有时候使用MyEclipse启动Tomcat十分缓慢,可能在几分钟前20秒以内,但现在却需要200秒开外:其间内存和CPU都被占用地厉害,而控制台的输出 ...

  4. 修改已经提交到远端的git commit信息

    有这么一种场景,就是以前没有设置用户名和邮箱,导致提交时git commit信息中用户信息不正确.这样的情况导致后来我们提交代码到git上面时因为身份验证错误,只有到 push 阶段了才发现提交不上去 ...

  5. apache配置重写

    linux环境下 <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-d Rewrite ...

  6. [C语言练习]万年历加强版

    /** * @copyright 2011 Chunhui Wang * * wangchunhui@wangchunhui.cn */ #include<stdio.h> int mai ...

  7. IO-03. 求整数均值

    /** *A3-IO-03. 求整数均值(10) *C语言实现 *测试已通过 */ #include "stdio.h" int main() { int a,s,d,f; sca ...

  8. 好的组件,无须太复杂 – KISSY Slide 组件简介

    KISSY Slide 组件首页:http://gallery.kissyui.com/slide/1.1/guide/index.html V1.1 New Featurs Slide是一个幻灯切换 ...

  9. 可以使用QT给龙芯开发软件

    直接apt-get install libqt5core5a就有了,也许是一个很好的小众市场机会呢 至于系统,可以使用debian mips https://www.debian.org/devel/ ...

  10. Delphi资源文件(全面分析之位图、光标、图标、AVI、JPEG、Wave)

    几乎每个Windows应用程序都使用图标.图片.光标等资源.资源是程序的一部分,但是它是不可执行代码.下面我们就详细介绍资 源文件在Delphi5中建立和使用方法.  1.把资源放到Exe文件的优点  ...