简体   繁体   English

C# 关闭 mysql 连接不起作用,mysqli_connect(): (08004/1040): Too many connections

[英]C# closing mysql connection is not working, mysqli_connect(): (08004/1040): Too many connections

I'm getting this error on phpMyAdmin我在 phpMyAdmin 上收到此错误

mysqli_connect(): (08004/1040): Too many connections 

The only script that is using this DB:使用此数据库的唯一脚本:

public static bool checkIp(string ip)
        {
            Console.WriteLine("CHECKIP");

            try
            {
                string sql = " SELECT * FROM `Ip tables` ";
                MySqlConnection con = new MySqlConnection("host=hostname;user=username;password=password;database=database;");
                MySqlCommand cmd = new MySqlCommand(sql, con);
                con.Open();

                MySqlDataReader reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    if (ip == reader.GetString("Ip"))
                    {
                        Console.WriteLine("Benvenuto, " + reader.GetString("Name"));
                        con.Close();
                        return true;
                    }
                }
                con.Close();
                return false;
            }
            catch(SqlException exp)
            {
                throw new InvalidOperationException("Error", exp);
            }
        }

Does this code close the connection correctly or something is wrong?这段代码是正确关闭连接还是有问题?

EDIT: I added this block after the catch block编辑:我在 catch 块之后添加了这个块

    finally
    {
        if(con.State == System.Data.ConnectionState.Open)
        {
            con.Close();
        }
    }

Any better way to write the code?有没有更好的方法来编写代码? Would finaly block still run if return is executed?如果执行 return ,finaly 块还会运行吗?

You should put your query in a using statement like this:您应该将查询放在 using 语句中,如下所示:

string conString= "host=hostname;user=username;password=password;database=database;"

using (MySqlConnection con = new MySqlConnection(conString))
            {
                con.Open();

                using (MySqlCommand com = con.CreateCommand())
                {
                    com.CommandText = "SELECT * FROM `Ip tables`";

                    using (MySqlDataReader dr = com.ExecuteReader())
                    {
                         while (reader.Read())
                        {
                            if (ip == reader.GetString("Ip"))
                            {
                                Console.WriteLine("Benvenuto, " + reader.GetString("Name"));
                                con.Close();
                                return true;
                            }
                        }
                    }
                }
            }

This will automatically close the connection without having to state con.Close()这将自动关闭连接而无需声明con.Close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM