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

时间:2017-05-09 07:52:24

标签: c# ado.net database-connectivity

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

所以我创建了3个类,每个类都有一个方法来测试连接字符串,但代码是相同的,所以我在想是否有可能创建一个处理所有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;
                }
            }
        }
    }

那么在上面的过程中做任何更好的方法吗?

2 个答案:

答案 0 :(得分:2)

您可以定义这样的通用方法:

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;
        }
    }
}

答案 1 :(得分:0)

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

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;
        }
    }
}