asp-classic – 从ASP.Classic中的Web.Config读取ConnectionString

前端之家收集整理的这篇文章主要介绍了asp-classic – 从ASP.Classic中的Web.Config读取ConnectionString前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个ASP文件.其实我连接到DataBase与我的文件中的一个connectionString.
sConnString = "Driver={sql Server}; Server=localhost; Database=DB"

有没有办法从Web.Config中读取ConnectionString?

编辑:

得到它适用于:

' Imports a connection string from an xml file (usually web.config)
Function ImportConnectionString(webConfig,attrName,reformatDSN)
    Dim oXML,oNode,oChild,oAttr,dsn
    Set oXML=Server.CreateObject("Microsoft.XMLDOM")
    oXML.Async = "false"
    oXML.Load(Server.MapPath(webConfig))
    Set oNode = oXML.GetElementsByTagName("connectionStrings").Item(0) 
    Set oChild = oNode.GetElementsByTagName("add")
    ' Get the first match
    For Each oAttr in oChild 
        If  oAttr.getAttribute("name") = attrName then
            dsn = oAttr.getAttribute("connectionString")
            If reformatDSN Then
                ' Optionally reformat the connection string (adjust as needed)
                dsn = Replace(dsn,"User ID=","UID=")
                dsn = Replace(dsn,"Password=","PWD=")
                dsn = Replace(dsn,"Data Source=","Server=")
                dsn = Replace(dsn,"Initial Catalog=","Database=")
                dsn = Replace(dsn,"Persist Security Info=True;","")
                dsn = "Provider=MSDAsql;Driver={sql Server};" & dsn
            End If
            ImportConnectionString = dsn
            Exit Function
        End If
    Next
End Function

用法

dsn = ImportConnectionString("..\web.config","ConnectionStringName",false)
sql = "SELECT * FROM MyTable"
Set oConn = Server.CreateObject("ADODB.Connection")
Set oRS = Server.CreateObject("ADODB.RecordSet")
oConn.Open dsn
oRS.Open sql,oConn

If NOT oRS.EOF Then
   oRS.MoveFirst
   Do
      Response.Write("&nbsp; &nbsp; &nbsp;" &  oRS("Column1") & "<br/>")
      oRS.MoveNext
   Loop Until oRS.EOF
End If

谢谢您的帮助

解决方法

由于Web.Config文件是XML,所以只需将其加载到 XML DOM中即可访问其元素.
原文链接:https://www.f2er.com/aspnet/246464.html

猜你在找的asp.Net相关文章