MySqlReader在错误的地方
本文关键字:错误 MySqlReader | 更新日期: 2023-09-27 17:53:54
这段代码检查数据库中已有的用户信息,如果数据相同,则更新信息:
// Connection to the database.
DbConnect();
// If the Connection is sound, checks the Username and Password are the same as the input.
try
{
mySqlCommand = mySqlConnect.CreateCommand();
mySqlCommand.CommandText = Database_MySQLDef.SELECTFROMUSERS + "UserName = '" + UModel.Name + "' AND UserPassword = '" + UModel.Pwd + "';";
mySqlReader = mySqlCommand.ExecuteReader();
while (mySqlReader.Read())
{
// If the query could not be found, outputs an error.
if (UModel.Pwd != Convert.ToString(mySqlReader["UserPassword"]))
{
Console.WriteLine("Query does not match");
}
// If the query is found, changes the input of the password.
else
{
try
{
// Updates the UserPassword in the Db.
mySqlCommand = mySqlConnect.CreateCommand();
mySqlCommand.CommandText = Database_MySQLDef.UPDATEUSERS + "UserPassword = '" + UModel.ConfirmPwd + "' WHERE UserName = '" + UModel.Name + "';";
mySqlCommand.ExecuteNonQuery();
}
catch (MySqlException e)
{
Console.WriteLine(e.Message);
}
// Closes the Reader and empties the Command object.
mySqlReader.Close();
mySqlCommand.ExecuteNonQuery();
}
}
}
catch (MySqlException e)
{
Console.WriteLine(e.Message);
}
// When the query is finished, terminates the connection to the Database.
finally
{
if (mySqlConnect != null)
{
mySqlConnect.Close();
}
}
这是我几个月前刚开始写的,所以我知道它很丑。然而,目前的主要问题是,MySqlReader.Close()
的位置似乎是在错误的地方。现在的位置(在else
语句的try/catch
块之后)
catch (MySqlException e)
{
Console.WriteLine(e.Message);
}
// Closes the Reader and empties the Command object.
mySqlReader.Close();
mySqlCommand.ExecuteNonQuery();
返回错误:
已经有一个打开的数据读取器与此连接相关联,必须先关闭。
在else
语句 try/catch
块之前我本来有
else
{
try
{
// Closes the Reader and empties the Command object.
mySqlReader.Close();
mySqlCommand.ExecuteNonQuery();
给出错误:
reader已关闭,读取尝试无效。
谁能指出哪里出了问题,我能做些什么来解决它?
你应该从while
循环中跳出来,而不是从else
。在循环之后,您应该关闭阅读器并重新创建mySqlCommand
。像这样:
{
bool passwordFounded = false;
while (mySqlReader.Read())
{
if (UModel.Pwd != Convert.ToString(mySqlReader["UserPassword"]))
{
Console.WriteLine("Query does not match");
}
else
{
passwordFounded = true;
break;
}
}
// Closes the Reader and empties the Command object.
mySqlReader.Close();
if (passwordFounded)
{
try
{
// Updates the UserPassword in the Db.
mySqlCommand = mySqlConnect.CreateCommand();
mySqlCommand.CommandText = Database_MySQLDef.UPDATEUSERS + "UserPassword = '" + UModel.ConfirmPwd + "' WHERE UserName = '" + UModel.Name + "';";
mySqlCommand.ExecuteNonQuery();
}
catch (MySqlException e)
{
Console.WriteLine(e.Message);
}
}
}