asp读取数据库关联的2个表之间的数据并以JSON格式输出

ASP   2025-03-01 16:21   60   0  
<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<!--#include  file="aspJSON1.19.asp" -->
<%
'deepseek
' 定义数组来保存结果
Dim parentArray()
Dim childArray()

' 连接数据库
Dim conn, rsParent, rsChild
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Provider=SQLOLEDB;Data Source=(local);Initial Catalog=bds257174220_db;User ID=sa;Password=xfxfxf;"

' 查询父类数据
Set rsParent = Server.CreateObject("ADODB.Recordset")
rsParent.Open "select id, MingCheng from BDClass where ParentID='1' order by orders", conn,3,2
' 初始化父类数组
ReDim parentArray(rsParent.RecordCount - 1, 1)
' 循环父类数据
Dim i
i = 0
Do While Not rsParent.EOF
    parentArray(i, 0) = rsParent("id")
    parentArray(i, 1) = rsParent("MingCheng")
  
    ' 查询子类数据
    Set rsChild = Server.CreateObject("ADODB.Recordset")
    rsChild.Open "select C.Comid, C.Title, C.OutUrl, C.TJtitle, C.Logo, C.ZSstar from BDcompany T, Company C where T.Comid=C.Comid and C.IsPass=1 and T.classid='" & rsParent("id") & "' order by Orders, T.AddTime desc, T.ID desc", conn,3,2
  
    ' 初始化子类数组
    ReDim childArray(rsChild.RecordCount - 1, 5)
  
    ' 循环子类数据
    Dim j
    j = 0
    Do While Not rsChild.EOF
        childArray(j, 0) = rsChild("Comid")
        childArray(j, 1) = rsChild("Title")
        childArray(j, 2) = rsChild("OutUrl")
        childArray(j, 3) = rsChild("TJtitle")
        childArray(j, 4) = rsChild("Logo")
        childArray(j, 5) = rsChild("ZSstar")
        rsChild.MoveNext
        j = j + 1
    Loop
  
    ' 将子类数组保存到一个新的父类数组元素中
    ' 使用动态数组来存储子类数据
    ReDim Preserve parentArray(UBound(parentArray, 1), 2)
    parentArray(i, 2) = childArray
    rsParent.MoveNext
    i = i + 1
Loop

' 关闭记录集和连接
rsParent.Close
Set rsParent = Nothing
rsChild.Close
Set rsChild = Nothing
conn.Close
Set conn = Nothing

' 使用 aspJSON 类将 parentArray 转换为 JSON 格式
Dim json, parentJson, childJson
Set json = New aspJSON

For i = 0 To UBound(parentArray, 1)
    Set parentJson = json.AddToCollection(json.data) ' 正确通过 json 对象调用 AddToCollection
    parentJson.Add "id", parentArray(i, 0)
    parentJson.Add "MingCheng", parentArray(i, 1)
  
    If IsArray(parentArray(i, 2)) Then
        For j = 0 To UBound(parentArray(i, 2), 1)
            Set childJson = json.AddToCollection(parentJson) ' 添加子元素
            childJson.Add "Comid", parentArray(i, 2)(j, 0)
            childJson.Add "Title", parentArray(i, 2)(j, 1)
            childJson.Add "OutUrl", parentArray(i, 2)(j, 2)
            childJson.Add "TJtitle", parentArray(i, 2)(j, 3)
            childJson.Add "Logo", parentArray(i, 2)(j, 4)
            childJson.Add "ZSstar", parentArray(i, 2)(j, 5)
        Next
    End If
Next

' 输出 JSON 格式的字符串
Response.Write json.JSONoutput()
%>


博客评论
还没有人评论,赶紧抢个沙发~
发表评论
说明:请文明发言,共建和谐网络,您的个人信息不会被公开显示。