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

yipeiwu_com5年前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()

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

相关文章

CentOS 6.5下安装Python 3.5.2(与Python2并存)

本文主要给大家介绍了关于CentOS 6.5 安装Python 3.5.2并与Python2并存的相关内容,分享出来供大家参考学习,下面来看看详细的介绍: 安装步骤如下 1、准备编译环境...

pandas 层次化索引的实现方法

层次化索引是pandas的一项重要功能,它使你能在一个轴上拥有多个(两个以上)索引级别。 创建一个Series,并用一个由列表或数组组成的列表作为索引。 data=Series(np...

Python实现生成随机日期字符串的方法示例

本文实例讲述了Python实现生成随机日期字符串的方法。分享给大家供大家参考,具体如下: 生成随机的日期字符串,用于插入数据库。 通过时间元组设定一个时间段,开始和结尾时间转换成时间戳。...

python判断字符串编码的简单实现方法(使用chardet)

本文实例讲述了python判断字符串编码的方法。分享给大家供大家参考,具体如下: 安装chardet模块 chardet文件夹放在/usr/lib/python2.4/site-pack...

Python解析xml中dom元素的方法

本文实例讲述了Python解析xml中dom元素的方法。分享给大家供大家参考。具体实现方法如下: 复制代码 代码如下:from xml.dom import minidom try: &...