俩函数搞定asp的orm映射[原创]
俩函数搞定asp的orm映射
orm必须用到实体类,像C#这样的语言 写实体类挺痛苦的,除非用工具
而asp有个好处,因为他可以动态构建一个字符串并把此字符串动态解析为代码,也就是他的 execute 和 ExecuteGlobal 俩函数
下面这个函数是 实体类生成器 只要传入列名字符串就能生成 一个全局可用的类
'定义一个实体类
'clsname 自定义类名
'cols 列字符串逗号分隔
sub clsnew(clsname,cols)
dim p
p = "class "&clsname&" :public "&cols&":public cols:sub class_initialize():cols="""&cols&""":end sub:sub fill(a,rownum):dim b,i:b = split(cols,"",""):for i=0 to ubound(b):execute b(i)&""=""&a(i,rownum):next:end sub: end class"
'一个动态的类 通过传入逗号分隔的列名字符串 来定义类内部的变量属性
'实体类内部带有一个填充自己的方法,用结果集的二维数组来填充
ExecuteGlobal p
'全局执行完 以后 本页面到处可用此类了
end sub
'二维数组表转化为实体类数组
'clsname 类名
'a 记录集的二维数组
function orm(clsname,a)
dim r(),i,o
redim r(ubound(a,2))
for i=0 to ubound(a,2)
execute "set o = new "&clsname
o.fill a,i
set r(i)=o
next
orm = r
end function
'使用实例
sub testorm
dim cols,clsname
cols = "id,bookid,type1"
clsname = "booktype"
dim a,b,i
conn_open
getrsa "select top 20 id,bookid,type type1 from book_type",a
'getrsa是执行sql并取得结果数组的函数
'a是通过rs.getrows获得的二维数组
conn_close
clsnew clsname,cols
b = orm(clsname,a)
for i=0 to ubound(b)
echo b(i).id&" "&b(i).bookid&" "&b(i).type1&"<br/>"
'这里我们就达到了目的 再也不用写rs("id")这样的了 用点代替了括号和双引号
next
end sub
'附 执行sql的函数
sub getrsa(sql,a)
dim rs
set rs = conn.execute(sql)
if not rs.eof then
a = rs.getrows()
else
a = ""
end if
set rs = nothing
end sub
相关文档:
asp 中常用的文件处理函数 收藏
asp 中处理文件上传以及删除时常用的自定义函数
<%
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'所有自定义的VBS函数
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
function DeleteFile(Filename) '删除文件
&nbs ......
'函数名:GetMyTimeNumber()
'作 用:生成时间的整数
'参 数:lx ---- 时间整数的类型
' lx=0 到分钟 lx=1 到小时 lx=2 到天 lx=3 到月
'返回值:生成时间的整数值(最小到分钟)
'示 例:
'********************************* ......
1.记录集关闭之前再次打开:
------------------------------------
sql="select * from test"
rs.open sql,conn,1,1
if not rs.eof then
dim myName
myName=rs("name")
end if
sql="select * from myBook"
rs.open sql,conn,1,1
------------------------------------ ......
<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%Session.CodePage=65001%>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!-- #include file="../configinc/conndb.asp"-->
<!--#include file="../configi ......
conndb.asp
<%
Session.CodePage=65001
response.Charset="utf-8"
%>
<%
'数据库连接文件
dim conn
dim connstr
connstr="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+server.mappath("../date/#heihuhuhuajian.mdb")+";Jet OLEDB:Database Pass ......