C# using语句中未打开连接
在使用MySql时,我在我的aspnetcore应用程序中遇到以下错误 System.InvalidOperationException:连接必须有效且打开 位于MySql.Data.MySqlClient.MySqlCommand.ThrowException ex 在MySql.Data.MySqlClient.MySqlCommand.CheckState 位于MySql.Data.MySqlClient.MySqlCommand.ExecuteReaderCommandBehavior 位于bdtFood.Controllers.PersonController.GetAllInt32 id 在lambda_methodClosure,Object,Object[] 位于Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker。 d__28.下一步 以下是我使用的代码:C# using语句中未打开连接,c#,mysql,connection,C#,Mysql,Connection,在使用MySql时,我在我的aspnetcore应用程序中遇到以下错误 System.InvalidOperationException:连接必须有效且打开 位于MySql.Data.MySqlClient.MySqlCommand.ThrowException ex 在MySql.Data.MySqlClient.MySqlCommand.CheckState 位于MySql.Data.MySqlClient.MySqlCommand.ExecuteReaderCommandBehavior
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);
}
}
}
读卡器动作时,连接应打开。但事实并非如此。调试时,连接关闭。
编辑:MySqlDataReader;在控制器类中声明。您需要先打开SqlConnection,然后再使用它。using语句仅在对象不再使用时处理该对象。这就是为什么要在Paranshesis中声明的using块中使用的任何对象都需要ti实现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();
}
你不在我能看到的任何地方。当你还没有打开连接时,是什么让你认为应该打开连接的?当你开始使用命令时,SqlClient也不会自动打开连接。通过在适当的时间调用.Open和.Close来管理连接的状态。确定使用不会自动打开和关闭连接吗?我想是这样的。当不再使用连接时,使用将处理该连接。它不会自动打开连接。