App.config MySQL VB.Net 上的 2 个或更多 ConnectionString

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

我得到了一个代码,可以 return 我的 VB.Net 项目中 App.ConfigConnectionString。我的问题是我是调用 online1 还是 offline2 正在调用 offline2 值或者更可能调用默认值 .

我想获取基于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
            Else
                'Since they didnt provide the name of the connection string
                'just grab the default on from app.config
                sReturn = connection.ConnectionString
            End If
        Next
    End If
    Return sReturn
End Function

App.Config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <connectionStrings>
    <add name="online1" connectionString="SERVER=127.0.0.1; 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" />
  </connectionStrings>

</configuration>

只需使用:

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
        Else
            Throw New Exception("No default connection string")
        End If
    Else
        Dim conn = connStrings(name)
        If conn Is Nothing Then Throw New Exception("No connection string named " & name)
        Return conn.ConnectionString
    End If
End Function

如果您还没有

,则需要参考 System.Configuration

您的代码的问题在于,如果连接名称为 null 或空,您甚至不会执行循环并且不会 return 默认值(您只是 return "") .如果他们确实指定了一个名称,但它不是第一个,那么你 return 默认值并退出,即使还有更多连接要检查。