比较喜欢python的装饰器, 试了下一种用法,通过装饰器来传递sql,并执行返回结果
这个应用应该比较少
为了方便起见,直接使用了ironpython, 连接的mssql server
# -*- coding: utf-8 -*-import clrclr.addreference('system.data')from system.data import *from functools import wrapsconn_str = server=localhost;database=db_test;uid=sa;password=sa2008def mssql(sql): def handler_result(rs): rst = [] while rs.read(): rst.add(rs[0]) return rst def decorator(fn): @wraps(fn) def wrapper(*args, **kwargs): theconnection = sqlclient.sqlconnection(conn_str) theconnection.open() try: myaction = sqlclient.sqlcommand(sql, theconnection) myreader = myaction.executereader() except exception,ex: raise assertionerror(ex) rst_data = handler_result(myreader) kwargs[sql_rst] = rst_data result = fn(*args, **kwargs) myreader.close() theconnection.close() return result return wrapper return decorator@mssql(sql=select getdate())def get_data(sql_rst=): print sql_rst[0]get_data()
算是为了好玩吧,回看了下,可能实际用的机会不多