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

作者:agentwx 时间:2022-07-10 19:27:37 

比较喜欢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
0
投稿

猜你喜欢

  • Array.prototype.slice

    2010-05-07 12:43:00
  • 从算法入手讲解SQL Server的典型示例

    2008-12-18 14:51:00
  • Mysql的最大连接数怎样用java程序测试

    2009-01-14 12:05:00
  • [翻译]JavaScript中对象的层次与继承

    2008-12-31 13:36:00
  • tensorflow使用神经网络实现mnist分类

    2023-07-05 10:19:13
  • PHP中使用Memache作为进程锁的操作类分享

    2023-11-22 18:10:02
  • 获取Dom元素的X/Y坐标

    2009-10-10 12:49:00
  • PHP概率计算函数汇总

    2023-11-19 08:06:19
  • 2009淘宝网动画节日LOGO第一季

    2009-05-18 19:11:00
  • php常用字符串长度函数strlen()与mb_strlen()用法实例分析

    2023-11-14 13:47:51
  • 将SQL 2000日志迁移到SQL Server 2008

    2009-03-25 16:20:00
  • css实现图片倒影效果

    2007-11-05 18:29:00
  • 深入剖析SQL Server的六种数据移动方法

    2009-01-07 14:09:00
  • js实现GIF动图分解成多帧图片上传

    2023-08-15 00:06:38
  • 如何使用ASP实现网站的“目录树”管理

    2008-06-13 06:39:00
  • 如何用SA-FileUp上传一个单纯的HTML文件?

    2010-05-18 18:29:00
  • 如何查看access数据库中各元素的最大容量

    2007-08-28 12:44:00
  • 一个简单的鼠标划过切换效果js源码

    2010-06-21 10:55:00
  • bat和python批量重命名文件的实现代码

    2023-10-07 02:11:53
  • javascript读取Json数据并分页显示,支持键盘和滚轮翻页

    2010-01-06 13:03:00
  • asp之家 网络编程 m.aspxhome.com