简体   繁体   中英

"Connection must be valid and open" - DataReader problem

I'm trying to take from a DataBase all under aged users, but when I try to, System.InvalidOperationException: 'Connection must be valid and open.' pops up. It's a Windows Form app, so this happens when I press the button.

I have tried searching for the problem but I cant find the error. I have 5 more functions with the same syntax and they work just fine. This is the code I have:

public static List<User> Underage(MySqlConnection connection)
        {
            string query= string.Format("SELECT * FROM users WHERE age<18");
            MySqlCommand command = new MySqlCommand(query, connection);
            MySqlDataReader reader = command.ExecuteReader();

            List<User> underage= new List<User>();
            if (reader.HasRows)
            {
                User usu = new User();
                while (reader.Read())
                {
                    usu.id = reader.GetInt16(0);
                    usu.name = reader.GetString(1);
                    usu.surname= reader.GetString(2);
                    usu.email = reader.GetString(3);
                    usu.age= reader.GetInt16(4);
                    usu.birth = reader.GetDateTime(5);
                    usu.payment= reader.GetFloat(6);
                    underage.Add(usu);
                }
            }
            return underage;
        }

Thanks anyways and sorry if it's a stupid problem, but I just cant figure it out.

Thanks for clarifying my problem mjwills and Adyson, you were right, I forgot to open it. I have a function to open the connection which I used in every other method of my program but I forgot to add it in this one. Sorry and thank you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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