0

我正在创建一个控制台应用程序,它输出“密码”列和“用户名”列的内容。有谁知道每次密码和用户名行上出现新数据时我如何重写输出?

我曾想过每次都重新创建实例并以MySqlDataReader这种cmd.ExecuteReader()方式重新分配:

for (int a = 0; a == 0;)
    {
        MySqlCommand cmd = new MySqlCommand(query, connection);
        MySqlDataReader reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            Console.WriteLine("Username: " + reader.GetString("username"));
            Console.WriteLine("Password: " + reader.GetString("password") + "\n");
        }
                   
}

但这给出了这个错误:

MySql.Data.MySqlClient.MySqlException (0x80004005):已经有一个打开的 DataReader 与此 Connection 关联,必须先关闭。在 MySql.Data.MySqlClient.Interceptors.ExceptionInterceptor.Throw(Exception 异常) 在 MySql.Data.MySqlClient.MySqlConnection.Throw(Exception ex) 在 MySql.Data.MySqlClient.MySqlCommand.Throw(Exception ex) 在 MySql.Data.MySqlClient .MySqlCommand.CheckState() 在 MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior 行为) 在 MySql.Data.MySqlClient.MySqlCommand.ExecuteReader() 在 showaph.Program.Main(String[] args) 在 C:\Users\ utente\source\repos\showaph\Program.cs:riga 51

我该怎么解决?

这是我的完整代码:

namespace showaph
{
    class Program
    {            
        static void Main(string[] args)
        {
            try
            {
                MySqlConnection connection = new MySqlConnection("Server=sql7.freemysqlhosting.net; Port=3306; Database=sql7389377; Uid=sql7389377; Pwd=*******; ");              
                connection.Open();
                if (connection.State == ConnectionState.Open)
                {
                    Console.WriteLine("Connected \n");    
                }
                else
                {
                    Console.WriteLine("not connected");
                }
                string query = "SELECT * FROM users";
                MySqlCommand cmd = new MySqlCommand(query, connection);
                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Console.WriteLine("Username: " + reader.GetString("username"));
                        Console.WriteLine("Password: " + reader.GetString("password") + "\n");
                    }

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            Console.ReadLine();
        }
    }
}
4

1 回答 1

0

你需要关闭你的阅读器

using (MySqlDataReader reader = cmd.ExecuteReader())
{

    while (reader.Read())
    {
        Console.WriteLine("Username: " + reader.GetString("username"));
        Console.WriteLine("Password: " + reader.GetString("password") + "\n");
    }
                   
}

于 2021-01-31T21:05:08.217 回答