gpt4 book ai didi

C# MySQL ExecuteReader

转载 作者:行者123 更新时间:2023-11-29 10:50:58 25 4
gpt4 key购买 nike

我的 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 block ,该 block 应该关闭并处置 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;
}

关于C# MySQL ExecuteReader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43740341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com