C#杀死数据库死链接

来源:互联网 发布:淘宝天天特价有用吗 编辑:程序博客网 时间:2024/05/01 22:58

先连进MYSQL 下show processlist的查询可查出 processID 在把他杀掉
C#代码:

using System.Data.Odbc;
using System.Data;

  static public int KillSleepingConnections(int iMinSecondsToExpire)
  {
   string strSQL = "show processlist";
   System.Collections.ArrayList m_ProcessesToKill = new ArrayList();

   OdbcConnection myConn = new OdbcConnection(Global.strDBServer);
   OdbcCommand myCmd = new OdbcCommand(strSQL, myConn); 
   OdbcDataReader MyReader = null;

   try 
   { 
    myConn.Open();

    // Get a list of processes to kill.
    MyReader = myCmd.ExecuteReader();
    while (MyReader.Read())
    {
     // Find all processes sleeping with a timeout value higher than our threshold.
     int iPID = Convert.ToInt32(MyReader["Id"].ToString());
     string strState = MyReader["Command"].ToString();
     int iTime = Convert.ToInt32(MyReader["Time"].ToString());

     if (strState == "Sleep" && iTime >= iMinSecondsToExpire && iPID > 0)
     {
      m_ProcessesToKill.Add(iPID);
     }
    }

    MyReader.Close();
    foreach (int aPID in m_ProcessesToKill)
    {
     strSQL = "kill " + aPID;
     myCmd.CommandText = strSQL;
     myCmd.ExecuteNonQuery();
    }
   }
   catch (Exception excep)
   {
   }
   finally
   {
    if (MyReader != null && !MyReader.IsClosed)
    {
     MyReader.Close();
    }

    if (myConn != null && myConn.State == ConnectionState.Open)
    {
     myConn.Close();
    }
   }

   return m_ProcessesToKill.Count;
  }

KillSleepingConnections(100);

原创粉丝点击