asp中调用的一个问题

来源:百度知道 编辑:UC知道 时间:2024/06/19 19:14:29
<!--#include file="conn.asp"-->
<%
sub x()
sql="select * from Class order by ID"
Set rs= Server.CreateObject("ADODB.Recordset")
rs.open sql,conn,1,1
call y()
end sub

sub y()
do while not rs.eof
response.Write(rs("name"))
response.Write("<br>")
rs.movenext
loop
end sub

call x()
%>

为了简单起见,我将两个函数简单化来说明问题,当运行这段代码时候就会出现说函数y中的do while not rs.eof这句存在问题,说缺少对象:rs 这是怎么回事啊,rs不是在x函数中形成了吗,为何在调用y时说没有这个对象呢?这里主要不明白为什么会出现报错,缺少对象rs,要怎么写才正确呢?请高手赐教,不胜感激!!

错误原因: 你这里的rs是在sub x()中定义,在sub y()中rs不存在,rs("name"))也得不到值 。
解决方法: 将sub x()中的Set rs= Server.CreateObject("ADODB.Recordset")定义到sub x()外面,即是定义全局变量,而不是局部变量。
建议代码:
<%
dim sql,rs
Set rs = Server.CreateObject("ADODB.Recordset")

sub x()
sql = "select * from Class order by ID"
rs.open sql,conn,1,1
call y()
end sub

sub y()
do while not rs.eof
response.Write(rs("name"))
response.Write("<br>")
rs.movenext
loop
end sub

call x()