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

2025-02-27 17:55   57   0  
<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
'跃问,输出JSON格式
    Dim parentSql, childSql, conn, rsParent, rsChild, parentArray, childArray, jsonOutput, i, j
  
    ' 创建数据库连接
    Set conn = Server.CreateObject("ADODB.Connection")
    conn.Open "Provider=SQLOLEDB;Data Source=(local);Initial Catalog=db;User ID=sa;Password=123456;"
  
    ' 定义父类SQL语句
    parentSql = "SELECT id, MingCheng FROM BDClass WHERE ParentID='1' ORDER BY orders"
  
    ' 定义子类SQL语句
    childSql = "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='" & id & "' ORDER BY Orders, T.AddTime DESC, T.ID DESC"
  
    ' 查询父类数据并保存到数组中
    Set rsParent = conn.Execute(parentSql)
  
    If Not rsParent.EOF And Not rsParent.BOF Then
        parentArray = rsParent.GetRows()
    Else
        parentArray = Null
    End If
  
    rsParent.Close
  
    ' 定义JSON输出字符串
    jsonOutput = "["
  
    ' 检查是否有父类数据
    If Not IsNull(parentArray) Then
        ' 循环父类数组
        For i = 0 To UBound(parentArray, 2)
            ' 将父类数据添加到JSON输出中
            jsonOutput = jsonOutput & "{""id"":""" & parentArray(0, i) & """,""MingCheng"":""" & parentArray(1, i) & """},"
          
            ' 查询子类数据并保存到数组中
            id = parentArray(0, i) ' 获取当前父类的id
            Set rsChild = conn.Execute(Replace(childSql, "&id&", id))
          
            If Not rsChild.EOF And Not rsChild.BOF Then
                childArray = rsChild.GetRows()
            Else
                childArray = Null
            End If
          
            rsChild.Close
          
            ' 将子类数据添加到JSON输出中
            If Not IsNull(childArray) Then
                jsonOutput = jsonOutput & "["
                For j = 0 To UBound(childArray, 2)
                    jsonOutput = jsonOutput & "{""Comid"":""" & childArray(0, j) & """,""Title"":""" & childArray(1, j) & """,""OutUrl"":""" & childArray(2, j) & """,""TJtitle"":""" & childArray(3, j) & """,""Logo"":""" & childArray(4, j) & """,""ZSstar"":""" & childArray(5, j) & """},"
                Next
                jsonOutput = Left(jsonOutput, Len(jsonOutput) - 1) & "]," ' 移除最后一个多余的逗号
            Else
                jsonOutput = jsonOutput & "[],"
            End If
        Next
    End If
  
    ' 移除最后一个多余的逗号并闭合JSON数组
    jsonOutput = Left(jsonOutput, Len(jsonOutput) - 1) & "]"
  
    ' 输出JSON结果
    Response.Write jsonOutput

    ' 关闭数据库连接
    conn.Close
    Set conn = Nothing
%>


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