在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简单I/O操作示例

本文实例讲述了Python简单I/O操作。分享给大家供大家参考,具体如下: 文件: poem = ''' hello world ''' f = file('book.txt', '...

python base64 decode incorrect padding错误解决方法

python的base64.decodestring方法做base64解码时报错: 复制代码 代码如下: Traceback (most recent call last):  ...

详解Django缓存处理中Vary头部的使用

Vary 头部定义了缓存机制在构建其缓存键值时应当将哪个请求头标考虑在内。 例如,如果网页的内容取决于用户的语言偏好,该页面被称为根据语言而不同。 缺省情况下,Django 的缓存系统使...

详解python中Numpy的属性与创建矩阵

ndarray.ndim:维度 ndarray.shape:形状 ndarray.size:元素个数 ndarray.dtype:元素数据类型 ndarray.itemsize:字节大小...

Python 和 JS 有哪些相同之处

【嵌牛导读】Python 是一门运用很广泛的语言,自动化脚本、爬虫,甚至在深度学习领域也都有 Python 的身影。作为一名前端开发者,也了解 ES6 中的很多特性借鉴自 Python...