Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read ConnectionString from Web.Config in ASP.Classic

I have a ASP-File. Actually i connect to the DataBase with a connectionString in my file.

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

Is there a way to read the ConnectionString from the Web.Config?

EDIT:

Got it to work with:

' 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

Usage:

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

Thanks for the help

like image 474
Paks Avatar asked Dec 13 '12 11:12

Paks


1 Answers

Since the Web.Config file is XML, just load it into an XML DOM and access its elements that way.

like image 72
webaware Avatar answered Oct 24 '22 08:10

webaware