2)数据库访问层
数据访问层是与数据库进行交互的接口,这里我仅仅实现了mysql的访问接口。下面是代码:
数据访问层是与数据库进行交互的接口,这里我仅仅实现了mysql的访问接口。下面是代码:
import pymysql
import os
#用于测试
class EmptyModel:
def __init__(self,name=None):
self.TableName=name
#数据库帮助基类,相当于接口。其实对于python这种语言,这个类完全没必要存在.
#不过对于多种数据库支持时,还是有点用.
#注意:这里的参数是格式化到字符串,无法防止SQL注入。为了防止SQL注入,可以对SQL进行处理。
#一般来说最好的办法是真正参数化,但我看了一下pymysql,并没有提供真正参数化的方法。
class DbHelper:
def QueryByParam(self,sql,pms,EntityName,conn=None):
return []
def ExecuteCommand(self,sql,pms,conn=None):
return 0
#Mysql的访问类,基于pymysql.
class DbHelperMySql(DbHelper):
def __init__(self,CharsetName='utf8'):
self.CharsetName = CharsetName
if(self.CharsetName==''):
self.CharsetName='utf8'
def ExecuteCommand(self,sql,pms,conn=None):
theNeedCloseConn = False
if(conn==None):
conn=self.GetMySqlDbConnDefault()
theNeedCloseConn = True
theCursor = conn.cursor()
try:
theCursor.execute("set NAMES "+self.CharsetName) #保证字符集正确.
theRet = theCursor.execute(sql,pms)
finally:
theCursor.close()
if theNeedCloseConn:
conn.close()
return theRet
@s