C# MySQL 执行读取器

C# MySQL ExecuteReader

我的 C# 项目有问题。我使用 MySQL 数据库并使用来自 MySQL 网站的 MySQL 连接器驱动程序,但我的光标和连接有问题。事实上,Visual Studio 说不可能从第二个过程读取数据,因为游标已经打开但我在新过程调用之前关闭了游标。

这是我的代码:

static public Data loadData()
{
    Data database = new Data();
    myConnexion.Open();
    
    /// <summary>
    ///     Loading of the categories
    /// </summary> 
    MySqlCommand command = new MySqlCommand("getCategory", myConnexion);
    command.CommandType = System.Data.CommandType.StoredProcedure;
    MySqlDataReader cursor = command.ExecuteReader();

    while (cursor.Read())
    {
        int id = Convert.ToInt32(cursor["id"]);
        string categoryName = Convert.ToString(cursor["name"]);

        Category category = new Category(id, categoryName);
        database.addCategory(category);
    }
    cursor.Close();
    
    /// <summary>
    ///     Loading of the projects
    /// </summary>
    command = new MySqlCommand("getProject", myConnexion);
    command.CommandType = System.Data.CommandType.StoredProcedure;
    cursor = command.ExecuteReader();

    while (cursor.Read())
    {
        int idProject = Convert.ToInt32(cursor["id"]);
        string name = Convert.ToString(cursor["name"]);
        int idCategory = Convert.ToInt32(cursor["idCategory"]);

        Category category = database.getCategories()[idCategory];
        Project project = new Project(idProject, name, category);
        Link.addProject(project.getName(), category);
    }
    cursor.Close();

    myConnexion.Close();
    return database;
}

这是 Visual Studio 启动程序时的错误消息:

您可以尝试将 DataReader 转换为 using 块,它应该关闭并处理 DataReader。

static public Data loadData()
{
    Data database = new Data();
    myConnexion.Open();

    /// <summary>
    ///     Loading of the categories
    /// </summary> 
    MySqlCommand command = new MySqlCommand("getCategory", myConnexion);
    command.CommandType = System.Data.CommandType.StoredProcedure;
    using (var cursor = command.ExecuteReader())
    {
        while (cursor.Read())
        {
            int id = Convert.ToInt32(cursor["id"]);
            string categoryName = Convert.ToString(cursor["name"]);

            Category category = new Category(id, categoryName);
            database.addCategory(category);
        }
    }



    /// <summary>
    ///     Loading of the projects
    /// </summary>
    command = new MySqlCommand("getProject", myConnexion);
    command.CommandType = System.Data.CommandType.StoredProcedure;
    using(var cursor = command.ExecuteReader())
    {

        while (cursor.Read())
        {
            int idProject = Convert.ToInt32(cursor["id"]);
            string name = Convert.ToString(cursor["name"]);
            int idCategory = Convert.ToInt32(cursor["idCategory"]);

            Category category = database.getCategories()[idCategory];
            Project project = new Project(idProject, name, category);
            Link.addProject(project.getName(), category);
        }
    }

    myConnexion.Close();
    return database;
}