我的C#项目有问题。我使用MySQL数据库,使用来自MySQL网站的MySQL连接器驱动程序,但是光标和连接有问题。实际上,Visual说这不可能从第二个过程中读取数据,因为游标已经打开,但是在新过程调用之前我已经关闭了游标。
这是我的密码:
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的错误消息:

发布于 2017-05-02 14:42:24
您可以尝试将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;
}https://stackoverflow.com/questions/43740341
复制相似问题