首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查MySQL连接并刷新它

检查MySQL连接并刷新它
EN

Code Review用户
提问于 2014-01-06 09:39:49
回答 1查看 7.9K关注 0票数 2

我使用以下函数检查MySQL连接是否处于无效状态,或者是否达到了预定义的最大操作计数:

代码语言:javascript
复制
 /// <summary>
 /// Holds the amount of operations for the currently mysql-connection open
 /// </summary>
 private int connectionUsageCount = 0;

 /// <summary>
 /// The maximum usage count of the connection until it has to be refreshed
 /// </summary>
 private const int MAX_CONNECTION_USAGE_COUNT = 100;

 /// <summary>
 /// Holds the cached MySql Connection to the databse server.
 /// </summary>
 private MySqlConnection mySqlConnection;

 /// <summary>
 /// Checks the status of the sql connection and refreshes it when necessary.
 /// </summary>
 private void CheckSqlConnection()
 {
     // Check if the connection is in an invalid state or
     // the connection has to be refreshed and refresh it
     // when necessary
     if (mySqlConnection == null
         || mySqlConnection.State == System.Data.ConnectionState.Broken
         || mySqlConnection.State == System.Data.ConnectionState.Closed
         || connectionUsageCount >= MAX_CONNECTION_USAGE_COUNT)
     {
         // If the connection was already initialized, close and dispose it
         if (mySqlConnection != null)
         {
             // If connection is open, close it
             if (mySqlConnection.State != System.Data.ConnectionState.Broken
                 && mySqlConnection.State != System.Data.ConnectionState.Closed)
             {
                 mySqlConnection.Close();
             }

             mySqlConnection.Dispose();
             mySqlConnection = null;
         }

         // Create new connection 
         mySqlConnection = new MySqlConnection(this.ConnectionString.ToString());
     }
 }

有人能回顾一下这段代码并告诉我一些反馈吗?我不确定我是否涵盖了在使用mySqlConnection时可能导致错误的所有可能性。

EN

回答 1

Code Review用户

回答已采纳

发布于 2014-01-06 10:02:45

  1. 根据这个问题,您需要知道,调用Close并不一定会真正关闭连接,而只会将其放入连接池中。
  2. 没有理由做mySqlConnection = null;。您在下一条语句中为mySqlConnection分配了一个新值,因此将其设置为null没有任何效果。
  3. 这些医生可能有点过时了,但是他们说您可以多次调用Close,并且不会产生异常,所以您可以跳过检查,无条件地调用Close
票数 2
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/38675

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档