我已经为我的应用程序创建了一个通用的数据库处理程序类。
我使用的是本地数据库,所以这里使用了 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);
}
关于c# - 在 con.Open() 之前测试数据库连接是否正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13080436/