Asp-Classic

從 ASP.Classic 中的 Web.Config 讀取 ConnectionString

  • March 12, 2014

我有一個 ASP 文件。實際上,我使用文件中的 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("     " &  oRS("Column1") & "<br/>")
     oRS.MoveNext
  Loop Until oRS.EOF
End If

謝謝您的幫助

由於 Web.Config 文件是 XML,只需將其載入到XML DOM中並以這種方式訪問其元素。

引用自:https://stackoverflow.com/questions/13859344