【问题标题】:2 or More ConnectionString on App.config MySQL VB.NetApp.config MySQL VB.Net 上的 2 个或更多 ConnectionString
【发布时间】:2016-12-23 13:34:42
【问题描述】:

我的 VB.Net 项目中的代码可以从 App.Config 返回 ConnectionString。我的问题是我是否调用 online1offline2 调用 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>

【问题讨论】:

    标签: mysql vb.net app-config


    【解决方案1】:

    只需使用:

    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 或为空,您甚至不会执行循环并且不会返回默认值(您只需返回“”)。如果他们确实指定了一个名称并且它不是第一个,那么即使有更多连接要检查,您也返回默认值并退出。

    【讨论】:

      猜你喜欢
      • 2013-03-19
      • 2011-01-24
      • 1970-01-01
      • 2015-01-06
      • 2012-12-06
      • 2011-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多