转载注明出处 http://blog.csdn.net/xugangjava/article/details/7565420
接上篇,写两个适配器一个用于查询Query,一个用于Execute
######################################################################## #decorators def Query(fn): '''decorator of connection use this funciton can use conn to operator db using conn=None param to user conn''' def wrapper(*args, **kv): conn=connect() kv['conn']=conn try: return fn(*args, **kv) except: LogErr() raise finally: conn.close() return wrapper def Execute(fn): '''decorator of connection use this funciton can use conn to operator db using conn=None param to user conn''' def wrapper(*args, **kv): conn=connect() kv['conn']=conn try: result= fn(*args, **kv) conn.commit() return result except: conn.rollback() LogErr() raise finally: conn.close() return wrapper
######################################################################## #proc and function @Execute def procLogin(name,pwd,ip,mac,conn=None): cur=conn.cursor() uid,val,remark,opResult=0,0,'','' param=(name,pwd, AvailablePeopleNum,mac, Ip2Int(ip), ip,False,uid,val,remark,opResult) param=cur.callproc('Proc_login',param) uid,val,remark,opResult=param[-4],param[-3],param[-2],param[-1] user=None if val==2:user=findUserByID(conn,uid) return user,remark
在也没看到要吐的重复的try catch finally来管理connection了
执行完Execute里面就自动提交了,报错Execute里面就给回滚了,Query也是一样
修改一个bug where函数 对 sql > < = line的拼接有点问题
#where def where(**kv): keys='' params=[] for key in kv.keys(): if keys:keys+=' and ' else: keys=' where ' if key.endswith('_gt'): exp=key.replace('_gt',' > ') elif key.endswith('_lt'): exp=key.replace('_lt',' < ') elif key.endswith('_ge'): exp=key.replace('_ge',' >= ') elif key.endswith('_le'): exp=key.replace('_le',' <= ') elif key.endswith('_like'): exp=key.replace('_like',' like ') else: exp=key+'=' keys+=exp+'?' param=kv[key] if isinstance(param,unicode):param=param.encode('gbk') params.append(param) return keys,tuple(params)