gpt4 book ai didi

mysql - App.config MySQL VB.Net 上有 2 个或更多 ConnectionString

转载 作者:行者123 更新时间:2023-11-29 20:32:02 26 4
gpt4 key购买 nike

我得到了一个可以从 VB.Net 项目中的 App.Config 返回 ConnectionString 的代码。我的问题是我是否调用 online1offline2offline2 值正在被调用或更可能是默认值

我想获取基于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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com