我有一个代码,可以从我的VB.Net项目中的App.Config
返回ConnectionString。我的问题是,我是将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
应用配置
<?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或为空,则您甚至都不会执行循环,也不会返回默认值(只需返回“”)。如果他们确实指定了名称,而不是第一个名称,那么即使有更多要检查的连接,您也将返回默认名称并退出。
关于mysql - App.config MySQL VB.Net上的2个或更多ConnectionString,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38987387/