在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中,不用while和for循环遍历列表的实例

如下所示: a = [1, 2, 3, 8, 9] def printlist(l, index): if index == len(l): return else:...

基于进程内通讯的python聊天室实现方法

本文实例讲述了基于进程内通讯的python聊天室实现方法。分享给大家供大家参考。具体如下: #!/usr/bin/env python # Added by <ctang@re...

Python实现全角半角转换的方法

本文实例讲解了Python实现全角半角转换的方法,相信对于大家的Python学习能够起到一定的参考借鉴价值。如下所示: 一、全角半角转换概述: 全角字符unicode编码从65281~6...

Python中tell()方法的使用详解

 tell()方法返回的文件内的文件读/写指针的当前位置。 语法 以下是tell()方法的语法: fileObject.tell() 参数  &nbs...

Python绘制KS曲线的实现方法

Python绘制KS曲线的实现方法

python实现KS曲线,相关使用方法请参考上篇博客-R语言实现KS曲线 代码如下: ####################### PlotKS #################...