WinForm程序中实现用户登录验证,错误次数三次后,就禁止登录!通过数据库来记录errortimes的值!
注意:在一个数据库连接中,只能执行一个cmd.ExecuteReader()语句,不可以在同一个连接中,再次执行类似Update语句:
public void IncErrorTimes()
{
using (SqlConnection conn = new SqlConnection(@"Data Source=tianyu/SQLEXPRESS;AttachDBFilename=|DataDirectory|/MyTest.mdf;Integrated Security=true;User Instance=true"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "update T_User set ErrorTimes=ErrorTimes+1 where UserName=@username";
cmd.Parameters.Add(new SqlParameter("username", txtUserName.Text));
cmd.ExecuteNonQuery();
}
}
}
public void ResetErrorTimes()
{
using (SqlConnection conn = new SqlConnection(@"Data Source=tianyu/SQLEXPRESS;AttachDBFilename=|DataDirectory|/MyTest.mdf;Integrated Security=true;User Instance=true"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "update T_User set ErrorTimes=0 where UserName=@username";
cmd.Parameters.Add(new SqlParameter("username", txtUserName.Text));
cmd.ExecuteNonQuery();
}
}
}
private void btnLogin_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(@"Data Source=tianyu/SQLEXPRESS;AttachDBFilename=|DataDirectory|/MyTest.mdf;Integrated Security=true;User Instance=true"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from T_User where UserName=@username";
cmd.Parameters.Add(new SqlParameter("username", txtUserName.Text));
//cmd .Parameters .Add (new SqlParameter ("password",txtPassword .Text));
using (SqlDataReader reader = cmd.ExecuteReader())//在同一个连接中,使用了reader就不能在使用UPDATE之类的其他操作语句!
{
if (reader.Read())
{
int errortimes = reader.GetInt32(reader.GetOrdinal("ErrorTimes"));
if (errortimes <3)
{
string dbpassword = reader.GetString(reader.GetOrdinal("Password"));
if (dbpassword == txtPassword.Text)
{
MessageBox.Show("登录成功!");
ResetErrorTimes();
}
else
{
MessageBox.Show("用户密码错误,登录失败!");
IncErrorTimes();
return;
}
}
else
{
MessageBox.Show("登录次数过多,登录失败!");
return;
}
}
else
{
MessageBox.Show("用户名错误!");
}
}
}
}
}