是否有标准的 .NET 方法来测试 SqlConnection 字符串是否有效?
可能的重复:
如何检查连接字符串是否有效?
目前我'我这样做:
internal bool CheckConnection()
{
using (SqlConnection testConn = new SqlConnection(this.ConnectionString))
{
try
{
testConn.Open();
}
catch (SqlException)
{
return false;
}
}
return true;
}
有更好的方法吗?
Possible Duplicate:
How to check if connection string is valid?
Currently I'm doing it like this:
internal bool CheckConnection()
{
using (SqlConnection testConn = new SqlConnection(this.ConnectionString))
{
try
{
testConn.Open();
}
catch (SqlException)
{
return false;
}
}
return true;
}
Is there a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这几乎就是做到这一点的方法。尽管您也应该考虑处理其他一些异常类型。可能还有无法连接的其他原因除了 sql 问题之外, 到数据库服务器。
除了 SqlException 之外,Connection.Open 还可以抛出 InvalidOperationException 和 ArgumentException。此外,.Open 调用的 API 可能会引发其他类型的异常,这些异常也会渗透到您的代码中。事实上,这是极少数情况之一,最好处理基本异常并向用户显示其消息。 (一般经验法则是仅处理特定的例外情况。)
That is pretty much the way to do it. Though you should think about handling some other exception types as well. There can be other reasons why you don't connect to a db server besides a sql issue.
Connection.Open can throw InvalidOperationException and ArgumentException in addition to SqlException. Also the APIs that .Open calls can throw other types of exceptions that can percolate to your code as well. In fact, this is one of the rare instances when it might be preferable to handle the base exception and display its message to the user. (The general rule of thumb is to handle only the specific exceptions.)
不,没有……这是唯一的方法
,您可以捕获
SqlException
并根据异常中的Number
返回更多信息(如果失败)Nop, there's not... that's the only way
What you can is catching the
SqlException
and return a little more info inc ase of fail depending on theNumber
in the exception