C#简单验证并限制登录次数小示例
描述:提示用户输入用户名,密码,与数据库中的数据匹配,如果正确则提示登陆成功,否则,提示登陆失败 错误次数超过三次,提示登陆次数过多,禁止登陆
数据表示例:
1 //数据库中ErrorTimes的次数增加1 2 public void incError() 3 { 4 using (SqlConnection conn = new SqlConnection(@"Data Source=.SQLEXPRESS;AttachDBFilename=|DataDirectory|Database1.mdf;Integrated Security=True;User Instance=True")) 5 { 6 conn.Open(); 7 SqlCommand cmd1 = conn.CreateCommand(); 8 cmd1.CommandText = "update T_Users set ErrorTimes=ErrorTimes+1 where UserName=@UN"; 9 cmd1.Parameters.Add(new SqlParameter("UN", txtUsername.Text)); 10 cmd1.ExecuteNonQuery(); 11 12 } 13 } 14 //重置数据库中ErrorTimes的次数为0 15 public void clsError() 16 { 17 using (SqlConnection conn = new SqlConnection(@"Data Source=.SQLEXPRESS;AttachDBFilename=|DataDirectory|Database1.mdf;Integrated Security=True;User Instance=True")) 18 { 19 conn.Open(); 20 SqlCommand cmd1 = conn.CreateCommand(); 21 cmd1.CommandText = "update T_Users set ErrorTimes=0 where UserName=@UN"; 22 cmd1.Parameters.Add(new SqlParameter("UN", txtUsername.Text)); 23 cmd1.ExecuteNonQuery(); 24 25 } 26 27 private void button1_Click(object sender, EventArgs e) 28 { 29 //提示用户输入用户名,密码,与数据库中的数据匹配,如果正确则提示登陆成功,否则,提示登陆失败 30 ///错误次数超过三次,提示登陆次数过多,禁止登陆。 31 using (SqlConnection conn = new SqlConnection(@"Data Source=.SQLEXPRESS;AttachDBFilename=|DataDirectory|Database1.mdf;Integrated Security=True;User Instance=True")) 32 { 33 conn.Open(); 34 SqlCommand cmd = conn.CreateCommand(); 35 cmd.CommandText = "select * from T_Users where UserName=@UN"; 36 cmd.Parameters.Add(new SqlParameter("UN", txtUsername.Text)); 37 using (SqlDataReader reader = cmd.ExecuteReader()) 38 { 39 if (reader.Read()) 40 { 41 int errortimes = reader.GetInt32(reader.GetOrdinal("ErrorTimes")); 42 if (errortimes > 3) 43 { 44 MessageBox.Show("错误次数过多,禁止登陆"); 45 } 46 string dbpassword = reader.GetString(reader.GetOrdinal("PassWord")); 47 if (dbpassword == txtPassword.Text) 48 { 49 MessageBox.Show("登陆成功"); 50 clsError(); 51 } 52 else 53 { 54 incError(); 55 MessageBox.Show("登陆失败"); 56 57 } 58 } 59 else 60 { 61 MessageBox.Show("用户名不存在"); 62 }