在con.open()之前,测试数据库连接还可以



我为我的应用创建了一个通用数据库处理程序类。

im使用本地数据库,因此在此使用SqlCeConnection类。

我想做的就是测试连接字符串有效,因此在执行connection.Open();

之前,请更新用户的连接状态

 SqlCeConnection conn = new SqlCeConnection(connectionString);
 //so far we have only created the connection, but not tried to open it
 //Would be nice to update the UI to say that conn is OK
 conn.testConnection();
 conn.Open();

我正在考虑编写一种尝试使用open然后close连接的方法,我在思考还是有更好的方法。

连接性测试添加了额外的开销。为什么不直接打开连接并将代码放入Try-Catch

try
{
    conn.Open();
}
catch(SqlCeException ex)
{
    // output the error to see what's going on
    MessageBox.Show(ex.Message); 
}

您可以将DbConnectionStringBuilder与属性ConnectionString一起使用,如果连接字符串不正确,它将抛出异常:

public static class Extension
{
    public static void TestConnection(this DbConnection connection)
    {
        var builder = new DbConnectionStringBuilder
            {
                ConnectionString = connection.ConnectionString
            };
    }
}

以这种方式,您无需真正与数据库打开连接。

最新更新