Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在con.Open()之前测试数据库连接是否正常_C#_Sql_Database_Sql Server Ce - Fatal编程技术网

C# 在con.Open()之前测试数据库连接是否正常

C# 在con.Open()之前测试数据库连接是否正常,c#,sql,database,sql-server-ce,C#,Sql,Database,Sql Server Ce,我已经为我的应用程序创建了一个通用数据库处理程序类 我使用的是本地数据库,所以这里使用的是SqlCeConnection类 我想做的是测试连接字符串是否有效,因此在执行Connection.Open()之前,向用户更新连接状态 比方说 SqlCeConnection conn = new SqlCeConnection(connectionString); //so far we have only created the connection, but not tried to open

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

我使用的是本地数据库,所以这里使用的是
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();

我正在考虑编写一种方法,尝试
打开
然后
关闭
连接,我这样想是对的还是有更好的方法。

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

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

您可以将
DbConnectionStringBuilder
与属性
ConnectionString
一起使用,它将在以下情况下引发异常:


通过这种方式,您不需要真正打开与数据库的连接。

这是一个本地数据库,因此服务器是本地主机,是否最好尝试catch?就像使用电子邮件地址一样,真正知道它有效的唯一方法是尝试并使用它。在这种情况下,即打开测试连接。打开(和关闭)连接只需很少的时间。所以就写吧。我也会利用
最终
,并用
TestConnection
方法将其全部抽象出来:
如果(!TestConnection(..){bathror(..)}
我喜欢这个想法,我试过了,但现在编译器给了我一个错误->错误1扩展方法必须在非泛型静态类C:\……\WindowsFormsApplication\Classes\DatabaseConnection.cs11中定义18@IEnumerable:将此代码放在静态类扩展上,编辑我的答案
public static class Extension
{
    public static void TestConnection(this DbConnection connection)
    {
        var builder = new DbConnectionStringBuilder
            {
                ConnectionString = connection.ConnectionString
            };
    }
}