测试各种rdbms连接字符串的通用方法

Generic way to test connection string of various rdbms

我有不同的数据源,如 mysql、SQL Server 和 Oracle,对于每个数据源,我将根据连接测试与服务器的握手是否成功字符串.

所以我创建了 3 个 class 并且每个 class 都有一个测试连接字符串的方法但是代码是相同的所以我在想是否可以创建 1将处理所有 3 个数据源的通用方法,如 mysql、SQL Server 和 Oracle,这样我就不必为每个数据源创建 3 个方法来测试连接字符串。

下面是我的代码:

public class ConnectionViewModel
    {
        public string RdbmsType { get; set; }
        public string  ConnectionString { get; set; }
    }

 [HttpPost]
        public ActionResult RdbmsServerHandshake(ConnectionViewModel model)
        {
             if (model.RdbmsType =="Mysql")
                {
                     var mySqlRepo = new MysqlRepository();
                     var test = mySqlRepo.TestConnectionString(model.ConnectionString);
                }
                else if(model.RdbmsType == "SqlServer")
                {
                     var sqlServerRepo = new SqlServerRepository();
                     var test = sqlServerRepo.TestConnectionString(model.ConnectionString);
                }
                else // for oracle
                {
                   // code for oracle
                }
        }

    public class SqlServerRepository
    {
        public bool TestConnectionString(string connectionString)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                try
                {
                    connection.Open();
                    return true;
                }
                catch (SqlException)
                {
                    return false;
                }
            }
        }
    }

    public class MysqlRepository
    {
        public bool TestConnectionString(string connectionString)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                try
                {
                    connection.Open();
                    return true;
                }
                catch (SqlException)
                {
                    return false;
                }
            }
        }
    }

所以有更好的方法来完成上述过程吗?

您可以像这样定义泛型方法:

static bool TestConnectionString<T>(string connectionString) where T : DbConnection, new()
{
    using (DbConnection connection = new T())
    {
        connection.ConnectionString = connectionString;

        try
        {
            connection.Open();
            return true;
        }
        catch (SqlException)
        {
            return false;
        }
    }
}

您应该关闭连接。否则,您将继续打开连接并保持打开状态。类似于亚历山德罗的回答,但代码中包含关闭:

static bool TestConnectionString<T>(string connectionString) where T : DbConnection, new()
{
    using (DbConnection connection = new T())
    {
        connection.ConnectionString = connectionString;

        try
        {
            connection.Open();
            connection.Close();
            return true;
        }
        catch (SqlException)
        {
            return false;
        }
    }
}