如何验证ConnectionString是否存在,如果不存在则不抛出错误

本文关键字:不存在 如果不 如果 错误 出错 存在 何验证 验证 是否 ConnectionString | 更新日期: 2023-09-27 18:01:15

在应用程序配置中找不到连接名'MySqlServer'或连接字符串为空。

所以,我有一个带有面板的页面,当发现web配置中的连接并且连接有效时将显示;使用try/catch只要添加名称"VALUE"在配置连接字符串中,如果服务器数据不好,页面将加载,面板设置为不可见…我需要能够处理以下内容…

如果指定的值在这种情况下MySqlServer在aspx;我不希望这个错误发生;没有找到连接名称....我只是不想显示面板,当SqlConnection。当找到名称但数据错误时,打开失败…

aspx

   <asp:SqlDataSource runat="server" ID="allowedIPsSqlDataSource" 
    ConnectionString="<%$ ConnectionStrings:MySqlServer %>"

aspx.cs

string connectionString = ConfigurationManager.ConnectionStrings["MySqlServer"].ToString();
        SqlConnection SqlConnection = new SqlConnection(connectionString);
        SqlCommand SqlCommand = new SqlCommand();
        try
        {
            SqlConnection.Open();

设置
<connectionStrings>
        <add name="NotMySqlServer" providerName="System.Data.SqlClient" connectionString="server=TEST'SQL2005;database=ADB;Integrated Security=True"/>
<add name="NotMy2SqlServer" providerName="System.Data.SqlClient" connectionString="server=TEST'SQL2005;database=ADB;Integrated Security=True"/>
    </connectionStrings>

如何验证ConnectionString是否存在,如果不存在则不抛出错误

您可以尝试:

if(ConfigurationManager.ConnectionStrings["MySqlServer"] == null) throw ...

如果你正在使用。net 4.5+并且可以访问c# 6.0,你可以使用null条件运算符(?)来尝试获得连接字符串而不会自动抛出异常:

string connectionString = ConfigurationManager.ConnectionStrings["MySqlServer"]?.ConnectionString;
//------------------------------------------------------------------------HERE-^-HERE-------------
if (string.IsNullOrWhiteSpace(connectionString))
{
    // Don't even bother trying to open the connection.
    // Log the error and either rethrow the exception (throw;) or exit from your current context (return;).
    //return;
    //throw;
}
// If your code has made it this far, it means you have a valid connection string.  Now try to use it.
using (var sqlConnection = new SqlConnection(connectionString))
{
    sqlConnection.Open();
    using (var sqlCommand = new SqlCommand)
    {
        // Do stuff.
    }
}

您可以使用count来检查是否存在连接字符串。

var count = ConfigurationManager.ConnectionStrings.Count;
if (count > 0)
{
    //There is at least more then one connection string.
}
更新

public static class Extension
{
    public static bool HasConnectionString(this ConnectionStringSettingsCollection value, string key)
{
    try
    {
        return value[key].ConnectionString.Length > 0;
    }catch 
    {
        return false;
    }
}
}

您可以使用扩展名如下:

if (ConfigurationManager.ConnectionStrings.HasConnectionString("MySqlServer"))
{
    //If true you know there is a valid connectionstring.
}