2016-08-17 7 views
0

VB.NetプロジェクトのApp.Configからのを返すことのできるコードがあります。私の問題は、オンライン1またはoffline2offline2の値が呼び出されているかどうかです。デフォルト値はです。2以上App.configのConnectionString MySQL VB.Net

私はApp.configファイル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 

に接続文字列ベースを取得したい

<?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> 

答えて

0

だけ使用します。

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または空の場合でもループを実行せず、デフォルトを返さない(単に ""を返す)ということです。彼らが名前を指定し、それが最初でない場合、チェックする接続がさらにある場合でもデフォルトを返して終了します。

+0

感謝の意:D – TKGhoul

関連する問題