<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>ASP无限级分类实现</title>
</head>
<body>
<%
Const IsSql = 0 '定义数据库类型,1为SQL Server,0为Access
Function OpenConn(Conn) '打开数据库连接
Dim ConnStr
If IsSql = 1 Then '如果是SQL Server数据库
'SQL Server数据库连接参数:用户名、用户密码、数据库名、连接名(本地用local,外地用IP)
Dim SqlUsername,SqlPassword,SqlDatabaseName,SqlLocalName
SqlUsername = "sa"
SqlPassword = ""
SqlDatabaseName = "TreeDb"
SqlLocalName = "(local)"
ConnStr = "Provider = Sqloledb; User ID = " & SqlUsername & "; Password = " & SqlPassword & "; Initial Catalog = " & SqlDatabaseName & "; Data Source = " & SqlLocalName & ";"
Else '如果是Access数据库
Dim Db
'第一次使用请修改本处数据库地址并相应修改数据库名称,如将Dicky.mdb修改为Dicky.asp(防止恶意下载Access数据库)
Db = "TreeDB.mdb"
ConnStr = "Provider = Microsoft.Jet.OLEDB.4.0;Data Source = " & Server.MapPath(Db)
End If
On Error Resume Next
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open ConnStr
If Err Then
' Err.Clear
Set Conn = Nothing
Response.Write "数据库连接出错,请检查连接字串。"
Response.End
End If
End Function
Function CloseConn(Conn) '关闭数据库连接
If IsObject(Conn) Then
Conn.Close
Set Conn = Nothing
End If
End Function
Function Echo(Str) '输出字符串并换行
Response.Write Str & VbCrlf
End Function
Call OpenConn(Conn)
'定义第一级分类
Sub MainFl()
Dim Rs
Set Rs = Conn.Execute("SELECT ClassID,ClassName FROM Class WHERE ParentClassID IS NULL")
If Not Rs.Eof Then
Do While Not Rs.Eof
Echo("<div><label id=""" & Trim(Rs("ClassID")) & """>+" & Trim(Rs("ClassName")) & "</label>")
Call Subfl(Rs("ClassID"),"|-") '循环子级分类
Echo("</div>")
Rs.MoveNext
If Rs.Eof Then Exit Do '防上造成死循环
Loop
End If
Set Rs = Nothing
End Sub
'定义子级分类
Sub SubFl(FID,StrDis)
Dim Rs1
Set Rs1 = Conn.Execute("SELECT ClassID,ClassName FROM Class WHERE ParentClassID = '" & FID & "'")
If Not Rs1.Eof Then
Do While Not Rs1.Eof
Echo(" <div id=""" & Trim(Rs1("ClassID")) & """>" & StrDis & Trim(Rs1("ClassName")) & "</div>")
Call SubFl(Trim(Rs1("ClassID")),"| " & Strdis) '递归子级分类
Rs1.Movenext:Loop
If Rs1.Eof Then
Rs1.Close
Exit Sub
End If
End If
Set Rs1 = Nothing
End Sub
'最后直接调用MainFl()就行了
MainFl()
Call CloseConn(Conn)%>
</body>
</html>