在ironpython中利用裝飾器執行SQL操作的例子
這篇文章主要介紹了在ironpython中利用裝飾器執行SQL操作的例子,文章中以操作MySQL為例,需要的朋友可以參考下
比較喜歡python的裝飾器, 試了下一種用法,通過裝飾器來傳遞sql,並執行返回結果
這個應用應該比較少
為了方便起見,直接使用了ironpython, 串連的mssql server
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42 |
# -*- 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()
|
算是為了好玩吧,回看了下,可能實際用的機會不多
注< >:更多精彩教程請關注幫客之家編程