现在相对简单多了,如果有多个操作页面我们只要导入连接文件就可以了,不过还是不够简洁,哪里不简洁? 一直在创建server,一直在写close,这样很容易出错,并且看起来与内容无关的太多。
那我再改进下: 把conn.asp文件改成: <% Dim Conn Dim Rs Sub CloseDatabase Conn.close Set Conn = Nothing End Sub Sub OpenDatabase Dim StrServer,StrUid,StrSaPwd,StrDbName StrServer="192.168.1.1" '数据库服务器名 StrUid="sa" '您的登录帐号 StrSaPwd="" '您的登录密码 StrDbName="cnbruce.mdb" '您的数据库名称 Set Conn = Server.CreateObject("ADODB.Connection") '用于连接ACCESS Conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Server.MapPath(StrDbName) '用于连接MSSQL 'Conn.ConnectionString = "Driver={sql server};driver={SQL server};server="&StrServer&";uid="&StrUid&";pwd="&StrSaPwd&";database= "&StrDbName set rs=server.CreateObject("ADODB.RecordSet") conn.open if Err Then err.Clear Set Conn = Nothing GBL_CHK_TempStr = GBL_CHK_TempStr & "数据库连接错误!" Response.Write GBL_CHK_TempStr Response.End End If End Sub %>
现在我们的showit.asp可以这样写:
showit.asp <!--#include file="conn.asp" --> <% sql = "Select * from cnarticle" opendatabase rs.Open sql,conn,1,1 If not Rs.eof then Do Until rs.EOF response.write("文章标题是:"& rs("cn_title")) response.write("<br>文章作者是:"& rs("cn_author")) response.write("<br>文章加入时间是:"& rs("cn_time")) response.write("<br>文章内容是:"& rs("cn_content")) response.write("<hr>") rs.MoveNext Loop else response.write ("暂时还没有文章") end if Closedatabase %>
嗯,我们又少写了一些东西,这样是最简单的吗?当然不是!还可以更简单。 使用GetRows把查询出来的数据传给一个变量,使用ubound方法取得数据记录条数。 不明白?没关系,让我们继续往下看:
再建个文件:sql.asp
sql.asp <% Class DataTable public Function SelectData(sql) If sql<>"" then opendatabase Rs.open sql,conn,1,1 If not Rs.eof then Thedata=Rs.GetRows(-1) Closedatabase Else Closedatabase End If End If SelectData=Thedata End Function End Class %>
嗯,复制它就可以了,现在我们的showit.asp可以简单地这样写:
showit.asp <!--#include file="conn.asp" --> <!--#include file="sql.asp" --> <% sql = "Select * from cnarticle" set loadData=new DataTable Thedata=loadData.SelectData(sql) If isarray(Thedata) then Num=ubound(Thedata,2) for i=0 to Num response.write("文章标题是:"& Thedata(1,i)) response.write("<br>文章作者是:"& Thedata(2,i)) response.write("<br>文章加入时间是:"& Thedata(3,i)) response.write("<br>文章内容是:"& Thedata(4,i)) response.write("<hr>") next else response.write("暂时还没有文章") End If %>
呵呵,这样,我们只要用两句语句就完成了数据的读取。同样的,通过在sql.asp中加入:
<% public Function SelectDataNum(sql) If sql<>"" then Opendatabase Rs.open sql,conn,1,1 If not Rs.eof then Thedata=Rs.GetRows(-1) Closedatabase Num=ubound(Thedata,2) Else Closedatabase End If End If SelectDataNum=Num End Function %>
我们就可以使用:
<% sql = "Select * from cnarticle" set loadData=new DataTable Num=loadData.SelectDataNum(sql) %>
来取得记录条数,可以用于分页或者用户名是否重复的判断。
出处:蓝色理想
责任编辑:moby
上一页 asp快速开发方法之数据操作 [1] 下一页 asp快速开发方法之数据操作 [3]
◎进入论坛网络编程版块参加讨论
|