C#关闭mysql连接不起作用,mysqli_connect:08004/1040:连接太多

问题描述

我在phpMyAdmin上收到此错误

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

唯一使用此数据库的脚本:

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);
            }
        }

此代码是否正确关闭了连接或出现了问题?

编辑: 我在catch块之后添加了该块

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

还有更好的代码编写方式吗?如果执行return,finally块是否仍会运行?

解决方法

您应将查询放在如下的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;
                            }
                        }
                    }
                }
            }

这将自动关闭连接,而无需声明con.Close()

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...