自己写了一个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)

最新文章

  1. 【emWin】例程十:bmp图片显示
  2. Swift 3 迁移工作总结
  3. mongo3.x ssl版安装文件
  4. isScroll代码
  5. 万能脚本助Web执行底层Linux命令
  6. 矢量做图组件OTGisX的使用(类似Mapbase)
  7. mysql 超时 问题处理
  8. HDU 3410 Passing the Message
  9. 一个机器学习博客 ,包括 Standford公开课machine learning
  10. SuperMap 9D 实时数据服务学习笔记
  11. SpringBoot快速开始Hello World
  12. mysql 数据库安装
  13. 关于thinkphp3自动完成的笔记
  14. Spring Boot项目属性配置
  15. 解决debug到jdk源码时不能查看变量值的问题
  16. 被查封7周之后,全球最大BT网站“海盗湾”又重新活过来了【36kr】
  17. angularjs显示html片段
  18. 实战c++中的string系列--不要使用memset初始化string(一定别这么干)
  19. Java\学习——字符串
  20. JS计算两个日期之间的天数,时间差计算

热门文章

  1. Unix/Linux环境C编程入门教程(31) 数学函数带你战胜企业面试
  2. COM组件开发实践(七)---多线程ActiveX控件和自动调整ActiveX控件大小(上)
  3. MAC上python环境搭建
  4. IOS 掉用系统发短信
  5. 格而知之9:一些关于GCD的笔记
  6. QUARTZ CRON
  7. ARM LDR伪指令使用方法具体解释
  8. android视频录制、另一部手机实时观看方案
  9. ECShop2.7.2详细文件结构及模板结构目录名称
  10. webapi单元测试时出现的ConfigurationManager.ConnectionStrings为空错误