TKGhoul TKGhoul - 1 year ago 204 Question

2 or More ConnectionString on App.config MySQL VB.Net

I got a code that can return the ConnectionString from the

in my VB.Net project. My problem is whether I call online1 or offline2 the offline2 value is being called or more likely a default.

I want to get a connection string base on
GetConnectionString([ConnectionString Name])

Public Shared Function GetConnectionString(ByVal strConnection As String) As String
'Declare a string to hold the connection string
Dim sReturn As New String(" ")
Dim connections As ConnectionStringSettingsCollection = ConfigurationManager.ConnectionStrings
'Check to see if they provided a connection string name
If Not String.IsNullOrEmpty(strConnection) Then
For Each connection As ConnectionStringSettings In connections
If connection.Name = strConnection Then
'Retrieve the connection string fromt he app.config
sReturn = connection.ConnectionString
'Since they didnt provide the name of the connection string
'just grab the default on from app.config
sReturn = connection.ConnectionString
End If
End If
Return sReturn
End Function


<?xml version="1.0" encoding="utf-8" ?>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
<add name="online1" connectionString="SERVER=; DATABASE=lto_db; UID=root; PASSWORD=;" providerName="MySql.Data.MySqlClient" />
<add name="offline2" connectionString="SERVER=localhost; DATABASE=lto_db; UID=root; PASSWORD=;" providerName="MySql.Data.MySqlClient" />


Answer Source

Just use:

Public Shared Function GetConnectionString(ByVal name As String) As String
    Dim connStrings = System.Configuration.ConfigurationManager.ConnectionStrings
    If String.IsNullOrEmpty(name) Then
        If connStrings.Count > 0 Then
            Return connStrings(0).ConnectionString
            Throw New Exception("No default connection string")
        End If
        Dim conn = connStrings(name)
        If conn Is Nothing Then Throw New Exception("No connection string named " & name)
        Return conn.ConnectionString
    End If
End Function

You'll need a reference to System.Configuration if you don't have one already

The problem with your code is that if the connection name is null or empty you don't even execute the loop and don't return a default (you just return ""). If they do specify a name and it's not the first then you return the default and exit even if there are more connections to check.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download