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 类.
随机推荐
- 一个C#多线程的工作队列
多线程添加元素到队列中,队列根据绑定 的事件进行自动处理,可以设置WorkSequential属性来实现对队列处理的单线程(严格顺序处理)或者多线程处理(循序出队,但是 多线程处理,不保证对队列元素的 ...
- Linux系统编程(6)——文件系统
计算机的文件系统是一种存储和组织计算机数据的方法,它使得对其访问和查找变得容易,文件系统使用文件和树形目录的抽象逻辑概念代替了硬盘和光盘等物理设备使用数据块的概念,用户使用文件系统来保存数据不必关心数 ...
- bzoj1649 [Usaco2006 Dec]Cow Roller Coaster
Description The cows are building a roller coaster! They want your help to design as fun a roller co ...
- LintCode-A + B 用位操作模拟加法
class Solution { public: /* * @param a: The first integer * @param b: The second integer * @return: ...
- 企业OA面临的问题,以及解决问题的推荐
现在的企业不管大小都趋于软件话,而办公用的OA软件更是成为了企业中不可获取的一环,一个好的软件能让企业发展的更加顺利,而一个不合适的软件可能让公司哀声怨道反而起了反作用! OA ...
- 用到的Python运算符
假设变量a为10,变量b为20. 算术运算符 比较运算符 赋值运算符 逻辑运算符 运算符优先级 对于逻辑运算符,not的优先级最大,or的优先级最小.它们三个的优先级排序为:not > and ...
- 工作记录8:iOS 传值问题总结(7种传值完美介绍)
1.属性传值 前向后传值. 记住: /* 1: 属性传值第一步需要用到什么类型就定义什么样的属性 2: 从上一个页面到一个页面的选中方法里面将要传的值传到来(上一个页面)备注:这种方法只适用于上一个页 ...
- 放弃使用jQuery实现动画
在Web开发的圈子里,开发人员经常觉得CSS动画是一种高性能web动画技术.假设想让网页载入的更快一些,就应该用纯CSS动画.事实上这样的观点是错误的,非常多开发人员早就放弃了javascript的动 ...
- Starting httpd:Could not reliably determine the server's fully qualified domain name
#service httpd start #Starting httpd: httpd: Could not reliably determine the server's fully qualifi ...
- 【贪心】【Uva11292】 勇者斗恶龙
直接用白书上的翻译吧 例题1 勇者斗恶龙(The Dragon of Loowater, UVa 11292) 你的王国里有一条n个头的恶龙,你希望雇一些骑士把它杀死(即砍掉所有头).村里有m个骑士 ...