在ironpython中利用装饰器执行SQL操作的例子

yipeiwu_com6年前Python基础

比较喜欢python的装饰器, 试了下一种用法,通过装饰器来传递sql,并执行返回结果
这个应用应该比较少
为了方便起见,直接使用了ironpython, 连接的mssql server

# -*- coding: utf-8 -*-
import clr
clr.AddReference('System.Data')
from System.Data import *
from functools import wraps

conn_str = "server=localhost;database=DB_TEST;uid=sa;password=sa2008"

def 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()

算是为了好玩吧,回看了下,可能实际用的机会不多

相关文章

跟老齐学Python之正规地说一句话

小孩子刚刚开始学说话的时候,常常是一个字一个字地开始学,比如学说“饺子”,对他/她来讲,似乎有点难度,大人也聪明,于是就简化了,用“饺饺”来代替,其实就是让孩子学会一个字就能表达。当然,...

Python3中的2to3转换工具使用示例

python3与python2的还是有诸多的不同,比如说在2中: 复制代码 代码如下: print "Hello,World!"  raw_input()  在...

python函数的作用域及关键字详解

函数的作用域 python中的作用域分4种情况: L:local,局部作用域,即函数中定义的变量; E:enclosing,嵌套的父级函数的局部作用域,即包含此函数的上级函数...

Django xadmin开启搜索功能的实现

应用目录下adminx.py class EmailVerifyRecordAdmin(object): search_fields = ['code','email','sen...

详解Python 定时框架 Apscheduler原理及安装过程

详解Python 定时框架 Apscheduler原理及安装过程

在我们的日常工作自动化测试当中,几乎超过一半的功能都需要利用定时的任务来推动触发,例如在我们项目中有一个定时监控模块,根据自己设置的频率定时跑测试用例,定时检测是否存在线上紧急任务等等,...