Python学习笔记10-Python MysqlHelper ,MySql 辅助类
自己写了一个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 辅助类的更多相关文章
- python 学习笔记 10 -- 正則表達式
零.引言 在<Dive into Python>(深入python)中,第七章介绍正則表達式,开篇非常好的引出了正則表達式,以下借用一下:我们都知道python中字符串也有比較简单的方法, ...
- python 学习笔记 9 -- Python强大的自省简析
1. 什么是自省? 自省就是自我评价.自我反省.自我批评.自我调控和自我教育,是孔子提出的一种自我道德修养的方法.他说:“见贤思齐焉,见不贤而内自省也.”(<论语·里仁>)当然,我们今天不 ...
- python学习笔记(一):python简介和入门
最近重新开始学习python,之前也自学过一段时间python,对python还算有点了解,本次重新认识python,也算当写一个小小的教程.一.什么是python?python是一种面向对象.解释型 ...
- python学习笔记(python简史)
一.python介绍 python的创始人为吉多·范罗苏姆(Guido van Rossum) 目前python主要应用领域: ·云计算 ·WEB开发 ·科学运算.人工智能 ·系统运维 ·金融:量化交 ...
- python学习笔记(1)--python特点
python诞生于复杂的信息系统时代,是计算机时代演进的一种选择. python的特点,通用语言,脚本语言,跨平台语言.这门语言可以用于普适的计算,不局限于某一类应用,通用性是它的最大特点.pytho ...
- Python学习笔记 - day12 - Python操作NoSQL
NoSQL(非关系型数据库) NoSQL,指的是非关系型的数据库.NoSQL有时也称作Not Only SQL的缩写,是对不同于传统的关系型数据库的数据库管理系统的统称.用于超大规模数据的存储.(例如 ...
- python 学习笔记一——Python安装和IDLE使用
好吧,一直准备学点啥,前些日子也下好了一些python电子书,但之后又没影了.年龄大了,就是不爱学习了.那就现在开始吧. 安装python 3 Mac OS X会预装python 2,Linux的大多 ...
- python学习笔记之——python模块
1.python模块 Python 模块(Module),是一个 Python 文件,以 .py 结尾,包含了 Python 对象定义和Python语句. 模块让你能够有逻辑地组织你的 Python ...
- python学习笔记10(Python的内存管理)
用这张图激励一下自己,身边也就只有一位全栈数据工程师!!! 32. Python的内存管理 1. 对象的内存使用 对于整型和短字符串对象,一般内存中只有一个存储,多次引用.其他的长字符串和其他对象 ...
- Python 学习笔记10
念念不忘,必有回响. 今天继续学习Python 类.
随机推荐
- Red and Black(BFS or DFS) 分类: dfs bfs 2015-07-05 22:52 2人阅读 评论(0) 收藏
Description There is a rectangular room, covered with square tiles. Each tile is colored either red ...
- oracle常见错误类型
http://www.cnblogs.com/whyhappy/p/6232258.html
- 第四章 Linux环境
程序参数 main函数声明: int main(int argc, char *argv[]) 其中argc是接受到的参数个数,argv是存储参数的字符串数组. 或者声明为: main() 这样也 ...
- kvm 图形化安装
为了再后续查看方便,我还是完整的记录kvm图形化安装. 介于网络环境的原因,我选择NAT. 2,安装kvm前的准备工作 2.1 关闭防火墙 setenforce 0 vi /etc/sysco ...
- Eclipse关联Java源代码
一个很简单的技巧,不多说,直接贴图 1. 2 . 3.选择你jdk下的src.zip就可以了.搞定!
- django学习笔记一
django作为一个python的开源项目发布,其web框架采用了mtv设计模式 在目前一些较为成熟的大型网站中有不少网站的应用基于django开发,django作为一个重量型的web框架提供了以下的 ...
- oracle取分组的前N条数据
select * from(select animal,age,id, row_number()over(partition by animal order by age desc) row_num ...
- 出发 Let's Go
今天是中秋佳节,而恰好我这天过生日,晚上睡觉前又恰好听到温岚唱的祝我生日快乐,心里挺高兴的. 最近,由于公司需要,可能要学习Python和Tribon了,全是未知的,一点不了解的东西,也忽然想起了在这 ...
- JAVA byte有无符号数的转换
如果你只需要对英文文本的每个字节进行数据处理,则无需考虑有符号数和无符号数的转换问题: 但如果你需要对含有中文的文本进行字节处理,则可能需要考虑有无符号数的转换问题. 以下代码均为Java代码. 1. ...
- UVA 140 Bandwidth
题意: 给出一个n个节点的图G,和一个节点的排列,定义节点i的带宽为i和相邻节点在排列中的最远距离,而所有带宽的最大值就是图的带宽,求让图的带宽最小的排列. 分析: 列出所有可能的排列,记录当前找到的 ...