有没有在我的ASP.NET应用程序,一个简单的方法以编程方式找出MySQL数据库服务器是否已关闭?我的、应用程序、简单、方式

2023-09-04 05:30:25 作者:至冬.

我在我的ASP.NET应用程序使用MySQL(与MySQL .NET连接器),反正是有以编程方式检查数据库服务器是否处于关闭状态?我碰到MySQLConnection.Ping(),但遗憾的是不工作的方式,它应该(将连接必须先打开使用Open(),它也不断返回false即使数据库服务器再次可用)。我想出了唯一的解决办法是使用Open()方法,如果抛出一个异常,那么数据库服务器不可用,有没有更可靠的方式做到这一点?我读的地方,如预期,如果连接池的情况下,这可能会导致一个异常被抛出,即使数据库服务器已启动使用Open()可能无法正常工作。

如果你想详细信息,请阅读:

在我的应用程序,我记录所有的异常(开始我尝试将它们记录到数据库服务器 - 可能是相同的数据库服务器这是下降,但可能没有,这取决于配置 - 如果失败的异常被记录到一个文本文件)。现在,我要处理的情况下,如果数据库服务器宕机,通常会发生什么是异常会继续被抛出,几乎每个请求我的应用程序,这意味着该日志将全面与例外的另一个问题是,我会继续提供错​​误页面给用户(或者换句话说,用户将继续看到与它们对应用程序的每个请求错误页面),我想要做的是,如果一个数据库异常被抛出(的IE浏览器。型个MySqlException)检查数据库服务器是否启动,如果没有的话改变了一些标志,我的应用程序和服务,其中包含一些页面,如应用程序暂时不可用(该标志在HTTP模块和重定向或转移检查到该页面) 。我也打算让它使用SMS代理,这样我可以采取的行动给我发短信,但另外一个故事,并没有涉及到这个问题。

解决方案

 尝试{
    cmd.ExecuteNonQuery();
    //服务器已启动
}
抓住 {
    //服务器关闭
}
 
图解使用VS 2013创建asp.net mvc应用程序

I use MySQL in my ASP.NET app (with the MySQL .NET Connector), is there anyway to programmatically check whether the db server is down? I came across MySQLConnection.Ping() but unfortunately that doesn't work the way it should (the connection has to be opened first using Open(), also it keeps on returning false even if the DB Server becomes available again). The only solution I came up with is to use the Open() method, if that throws an exception then the DB server is not available, is there a more reliable way to do this? I read somewhere that using Open() might not work as expected if connection pooling is used, this could result an exception being thrown even if the DB server is up.

If you want the details please read on:

In my app, I log all exceptions (first I try to log them to the DB Server - could be the same DB Server that's down but could be not, depending on the configuration - if that fails the exceptions are logged to a text file). Now I want to handle the case if the DB server is down, normally what will happen is that exceptions will keep on being thrown with almost every request to my app, this means the log will be full with those exceptions, the other problem is that I'll keep on serving error pages to users (or in other words the users will keep on seeing error pages with every request they make to the app), what I want to do is that if a db exception is thrown (ie. of type MySQLException) to check whether the DB server is up, if not then change some flag in my app and serve a page that contains something like the application is temporarily unavailable (the flag is checked in an httpModule and redirects or transfers to that page). I'm also planning to make it send me an SMS using an SMS proxy so that I could take an action, but this another story and is not related to this question.

解决方案

try {
    cmd.ExecuteNonQuery();
    // server is up
}
catch { 
    // server is down
}