2012-12-13 10 views
10

Mam plik ASP. Właściwie to łączę się z DataBase za pomocą connectionString w moim pliku.Przeczytaj ConnectionString z Web.Config w ASP.Classic

sConnString = "Driver={SQL Server}; Server=localhost; Database=DB" 

Czy istnieje sposób odczytu ConnectionString z Web.Config?

EDIT:

Got go do pracy z:

' 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 

Zastosowanie:

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 

Dzięki za pomoc

Odpowiedz

5

Ponieważ plik web.config jest XML, po prostu załaduj go do XML DOM i uzyskaj dostęp do jego elementów w ten sposób.

+0

Dzięki link pomógł mi dużo – Paks

+0

również znalazłem [this page] (http://www.c-sharpcorner.com/UploadFile/sd_patel/WebConfigInASPNet11242005061608AM/WebConfigInASPNet.aspx), który pokazuje, jak wyodrębnić ciąg połączenia z web.config – mfeineis

+0

@vanhelgen Ta strona, którą połączyłeś, robi dokładnie to, co opisano w swojej odpowiedzi. – crush

Powiązane problemy