连接未在 using 语句中打开

Connection not open in using statement

在使用 MySql 时,我的 aspnetcore 应用出现以下错误。

System.InvalidOperationException: Connection must be valid and open.

at MySql.Data.MySqlClient.MySqlCommand.Throw(Exception ex)

at MySql.Data.MySqlClient.MySqlCommand.CheckState()

at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)

at bdtFood.Controllers.PersonController.GetAll(Int32 id)

at lambda_method(Closure , Object , Object[] )

at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker. d__28.MoveNext()

这是我使用的代码:

using (var connection = new MySqlConnection(myConnectionString))
using (var command = connection.CreateCommand())
{
    command.CommandText = "SELECT * FROM person";
    Modells.Person helpPerson;
    using (reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            helpPerson = new Modells.Person(reader.GetInt32(0), reader[1].ToString(), reader[2].ToString(), reader[3].ToString(), reader[4].ToString(), reader.GetInt32(5));
            persons.Add(helpPerson);
        }
    }
}

连接应该在 reader 动作时打开。但事实并非如此。调试时连接已关闭。 编辑:MySqlDataReader reader; 在控制器 class 中声明。

使用前需要先打开SqlConnectionusing 语句仅在对象不再使用时才释放该对象。这就是为什么您想在 using 块(在括号中声明)中使用的任何对象都需要 ti implement IDisposable 的原因。你的问题应该这样解决:

using (var connection = new MySqlConnection(myConnectionString))
using (var command = connection.CreateCommand())
{
    connection.Open();
    command.CommandText = "SELECT * FROM person";
    Modells.Person helpPerson;
    using (reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            helpPerson = new Modells.Person(reader.GetInt32(0), reader[1].ToString(), reader[2].ToString(), reader[3].ToString(), reader[4].ToString(), reader.GetInt32(5));
            persons.Add(helpPerson);
        }
    }

    connection.Close();
}