以下代码在if-else语句中显示消息框后抛出异常。例外情况是我的读者无法阅读,因为它已关闭:
try
{
using (MySqlConnection conn = new MySqlConnection(Config.ConnectionString()))
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * from tb_useraccounts;", conn);
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (UserName == (dr["username"].ToString()) && PassWord == (dr["password"].ToString()))
{
frmMain main = new frmMain();
main.Show();
login.Hide();
}
else if (UserName == string.Empty || PassWord == string.Empty)
{
MessageBox.Show("Please fill the blank spaces!");
}
else
{
MessageBox.Show("The username and password you inserted is incorrect!");
}
dr.Close();
conn.Close();
}
}
如何让while
循环正常工作?
答案 0 :(得分:0)
你必须在while循环之后关闭阅读器和连接,如下所示
try
{
using (MySqlConnection conn = new MySqlConnection(Config.ConnectionString()))
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * from tb_useraccounts;", conn);
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (UserName == (dr["username"].ToString()) && PassWord == (dr["password"].ToString()))
{
frmMain main = new frmMain();
main.Show();
login.Hide();
}
else if (UserName == string.Empty || PassWord == string.Empty)
{
MessageBox.Show("Please fill the blank spaces!");
}
else
{
MessageBox.Show("The username and password you inserted is incorrect!");
}
}
dr.Close();
conn.Close();
}