测试SQL连接而不会引发异常 [英] Test sql connection without throwing exception
问题描述
要测试我是否可以连接到数据库,我执行以下代码:
To test if i can connect to my database, I execute the following code :
using (SqlConnection connection = new SqlConnection(myConnectionString))
{
try
{
connection.Open();
canConnect = true;
}
catch (SqlException) { }
}
此除了在连接失败时抛出异常外,其他方法均有效。还有其他方法可以测试不会引发异常的Sql连接吗?
This works except it throws an exception if the connection failed. Is there any other way to test a Sql connection that doesn't throw an exception ?
编辑:
要增加精度,我要问是否有一个简单的方法,无需打开连接即可捕获可能发生的异常
Edit : To add precision, i'm asking if there is a simple method that does that without having to open the connection and catch exceptions that can occur
推荐答案
在尝试打开连接时,如果无法打开连接,则无法避免该异常。可以将其隐藏在某个函数中,但是无论如何您都会得到异常。
When attempting to open a connection, there is no way to avoid the exception if the connection can't be opened. It can be hidden away in a function somewhere, but you're going to get the exception, no matter what.
它的设计是这样的,因为通常您希望能够连接到数据库。失败的连接是 except 。
It was designed like this because generally you expect to be able to connect to the database. A failed connection is the exception.
可以这么说,您可以随时测试 current 连接状态通过检查州
属性。
That being said, you can test the current connection state at any time by checking the State
property.
这篇关于测试SQL连接而不会引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!