2012-12-13 80 views
10

我有一個ASP文件。其實我用我的文件中的connectionString連接到數據庫。從ASP.Classic中的Web.Config讀取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 

感謝您的幫助

回答

5

由於Web.config文件的XML,只是將它加載到一個XML DOM並以這種方式訪問​​它的元素。

+0

謝謝你的鏈接幫助了我很多 – Paks

+0

我也發現[此頁](http://www.c-sharpcorner.com/UploadFile/sd_patel/WebConfigInASPNet11242005061608AM/WebConfigInASPNet.aspx)展示瞭如何提取從一個連接字符串web.config – mfeineis

+0

@vanhelgen你鏈接的頁面正在做他的答案中描述的webaware。 – crush

相關問題