杀死MySQL的连接

命令  kill 执行线程号

C# 执行杀死指定的连接

1  强制Kill掉

        internal protected void KillConnection(MySqlConnection c)
        {
            int threadId = c.ServerThread;
            MySqlCommand cmd = new MySqlCommand("KILL " + threadId, conn);
            cmd.ExecuteNonQuery();

            // the kill flag might need a little prodding to do its thing
            try
            {
                cmd.CommandText = "SELECT 1";
                cmd.Connection = c;
                cmd.ExecuteNonQuery();
            }
            catch (Exception) { }

            // now wait till the process dies
            bool processStillAlive = false;
            while (true)
            {
                MySqlCommand cmdProcess = new MySqlCommand("SHOW PROCESSLIST", conn);
                MySqlDataReader dr = cmdProcess.ExecuteReader();
                while (dr.Read())
                {
                    if (dr.GetInt32(0) == threadId) processStillAlive = true;
                }
                dr.Close();

                if (!processStillAlive) break;
                System.Threading.Thread.Sleep(500);
            }
        }

        internal protected void KillPooledConnection(string connStr)
        {
            MySqlConnection c = new MySqlConnection(connStr);
            c.Open();
            KillConnection(c);
        }

  

 

 

2  友好的关闭连接

public void CloseConnection(MySqlConnection conn)
{
if (conn != null && conn.State != ConnectionState.Closed)
{
try
{
conn.Close();
conn.Dispose();
}
catch
{
}
}
}

 

posted @ 2016-08-09 10:50  特洛伊-Micro  阅读(1754)  评论(0编辑  收藏  举报