自己写了一个MySql辅助类,有需要的拿走:

#--encoding:utf-8--
#
import MySQLdb class MySQLHelper:
myVersion=0.1
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)
self.conn.set_character_set(self.charset)
self.cursor=self.conn.cursor()
except MySQLdb.Error as e:
print ('MySql Error : %d %s' %(e.args[0],e.args[1])) def setDB(self,db):
try:
self.conn.select_db(db)
except MySQLdb.Error as e:
print ('MySql Error : %d %s' %(e.args[0],e.args[1])) def query(self,sql):
try:
rows=self.cursor.execute(sql)
return rows;
except MySQLdb.Error as e:
print('MySql Error: %s SQL: %s'%(e,sql)) def queryOnlyRow(self,sql):
try:
self.query(sql)
result=self.cursor.fetchone()
desc=self.cursor.description
row={}
for i in range(0,len(result)):
row[desc[i][0]]=result[i]
return row;
except MySQLdb.Error as e:
print('MySql Error: %s SQL: %s'%(e,sql)) def queryAll(self,sql):
try:
self.query(sql)
result=self.cursor.fetchall()
desc=self.cursor.description
rows=[]
for cloumn in result:
row={}
for i in range(0,len(cloumn)):
row[desc[i][0]]=cloumn[i]
rows.append(row)
return rows;
except MySQLdb.Error as e:
print('MySql Error: %s SQL: %s'%(e,sql)) def insert(self,tableName,pData):
try:
newData={}
for key in pData:
newData[key]="'"+pData[key]+"'"
key=','.join(newData.keys())
value=','.join(newData.values())
sql="insert into "+tableName+"("+key+") values("+value+")"
self.query("set names 'utf8'")
self.query(sql)
self.commit()
except MySQLdb.Error as e:
self.conn.rollback()
print('MySql Error: %s %s'%(e.args[0],e.args[1]))
finally:
self.close() def update(self,tableName,pData,whereData):
try:
newData=[]
keys=pData.keys()
for i in keys:
item="%s=%s"%(i,"'"+pData[i]+"'")
newData.append(item)
items=','.join(newData)
newData2=[]
keys=whereData.keys()
for i in keys:
item="%s=%s"%(i,"'"+whereData[i]+"'")
newData2.append(item)
whereItems=" AND ".join(newData2)
sql="update "+tableName+" set "+items+" where "+whereItems
self.query("set names 'utf8'")
self.query(sql)
self.commit()
except MySQLdb.Error as e:
self.conn.rollback()
print('MySql Error: %s %s'%(e.args[0],e.args[1]))
finally:
self.close() def getLastInsertRowId(self):
return self.cursor.lastrowid def getRowCount(self):
return self.cursor.rowcount def commit(self):
self.conn.commit() def close(self):
self.cursor.close()
self.conn.close()

测试 代码:

#--encoding:utf-8--
#
from MySQLHelper import * helper=MySQLHelper("localhost","root","")
helper.setDB("employee")
sql="select * from users"
rows=helper.queryAll(sql)
for row in rows:
print row['id'],row['name'].decode("utf-8"),row['birthday'] # dataSource={"name":"汤姆克路斯".decode("gbk").encode("utf-8"),"birthday":"1992-03-12"}
# helper.insert("users", dataSource)
# print helper.getLastInsertRowId() # pData={"birthday":"2005-05-05 18:32:23"}
# whereData={"name":"Jack Tang"}
# helper.update("users", pData, whereData)

Python学习笔记10-Python MysqlHelper ,MySql 辅助类的更多相关文章

  1. python 学习笔记 10 -- 正則表達式

    零.引言 在<Dive into Python>(深入python)中,第七章介绍正則表達式,开篇非常好的引出了正則表達式,以下借用一下:我们都知道python中字符串也有比較简单的方法, ...

  2. python 学习笔记 9 -- Python强大的自省简析

    1. 什么是自省? 自省就是自我评价.自我反省.自我批评.自我调控和自我教育,是孔子提出的一种自我道德修养的方法.他说:“见贤思齐焉,见不贤而内自省也.”(<论语·里仁>)当然,我们今天不 ...

  3. python学习笔记(一):python简介和入门

    最近重新开始学习python,之前也自学过一段时间python,对python还算有点了解,本次重新认识python,也算当写一个小小的教程.一.什么是python?python是一种面向对象.解释型 ...

  4. python学习笔记(python简史)

    一.python介绍 python的创始人为吉多·范罗苏姆(Guido van Rossum) 目前python主要应用领域: ·云计算 ·WEB开发 ·科学运算.人工智能 ·系统运维 ·金融:量化交 ...

  5. python学习笔记(1)--python特点

    python诞生于复杂的信息系统时代,是计算机时代演进的一种选择. python的特点,通用语言,脚本语言,跨平台语言.这门语言可以用于普适的计算,不局限于某一类应用,通用性是它的最大特点.pytho ...

  6. Python学习笔记 - day12 - Python操作NoSQL

    NoSQL(非关系型数据库) NoSQL,指的是非关系型的数据库.NoSQL有时也称作Not Only SQL的缩写,是对不同于传统的关系型数据库的数据库管理系统的统称.用于超大规模数据的存储.(例如 ...

  7. python 学习笔记一——Python安装和IDLE使用

    好吧,一直准备学点啥,前些日子也下好了一些python电子书,但之后又没影了.年龄大了,就是不爱学习了.那就现在开始吧. 安装python 3 Mac OS X会预装python 2,Linux的大多 ...

  8. python学习笔记之——python模块

    1.python模块 Python 模块(Module),是一个 Python 文件,以 .py 结尾,包含了 Python 对象定义和Python语句. 模块让你能够有逻辑地组织你的 Python ...

  9. python学习笔记10(Python的内存管理)

      用这张图激励一下自己,身边也就只有一位全栈数据工程师!!! 32. Python的内存管理 1. 对象的内存使用 对于整型和短字符串对象,一般内存中只有一个存储,多次引用.其他的长字符串和其他对象 ...

  10. Python 学习笔记10

    念念不忘,必有回响. 今天继续学习Python 类.

随机推荐

  1. [Leetcode][Python]55: Jump Game

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 55: Jump Gamehttps://leetcode.com/probl ...

  2. Zookeeper 2、Zookeeper的安装和配置(集群模式)

    1.下载与解压 Zookeeper下载地址:http://www.apache.org/dyn/closer.cgi/zookeeper/ 下载完成以后解压到一个特定目录 同步时间所有节点的时间,并关 ...

  3. A Simple Problem with Integers(100棵树状数组)

    A Simple Problem with Integers Time Limit: 5000/1500 MS (Java/Others)    Memory Limit: 32768/32768 K ...

  4. Radar Installation(贪心,可以转化为今年暑假不ac类型)

    Radar Installation Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 20000/10000K (Java/Other) ...

  5. C#静态构造函数和析构函数片段化认知

    一.静态构造函数 一个类可以有静态构造函数,实现如下源代码.静态构造函数有以下特性: 1).静态构造函数不能有修饰符(润饰符) 2).静态构造函数不能有参数 3).不能被调用——在实例化类的时候,静态 ...

  6. Android应用程序请求SurfaceFlinger服务创建Surface的过程分析

    文章转载至CSDN社区罗升阳的安卓之旅,原文地址:http://blog.csdn.net/luoshengyang/article/details/7884628 前面我们已经学习过Android应 ...

  7. Hacker(五)----黑客专用通道--->端口

    计算机中,端口是计算机与外部进行通信交流的出口.计算机本身携带的物理端口(键盘.鼠标.显示器等输入/输出接口)已经无法满足网络通信的要求,因此TCP/IP协议就引入了一种称为Socket的应用程序接口 ...

  8. vlc-android对于通过Live555接收到音视频数据包后的处理分析

    通过ndk-gdb跟踪调试vlc-android来分析从连接到RTSP服务器并接收到音视频数据包后的处理过程. 首先,从前面的文章有分析过vlc-android的处理过程通过线程函数Run()(Src ...

  9. C# DES 加密解密

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.S ...

  10. Sharepoint2010 通过 WebFeature 修改web.config

    using System;using System.Runtime.InteropServices;using System.Security.Permissions;using Microsoft. ...