private void IncErrorTimes() //累加错误次数
{
using (SqlConnection conn = new SqlConnection(@"Data Source=.\Express;AttachDBFilename=|DataDirectory|\MyDB.mdf;Integrated Security=true;User Instance=false"))
{
conn.Open();
using (SqlCommand updateCmd = conn.CreateCommand())
{
updateCmd.CommandText = "update T_Users Set ErrorTimes=ErrorTimes+1 where UserName=@UserName"; //更新错误次数加1
updateCmd.Parameters.Add(new SqlParameter("UserName", txtUserName.Text));
updateCmd.ExecuteNonQuery();
}
}
}
private void ResetErrorTimes() //重置错误次数
{
using (SqlConnection conn = new SqlConnection(@"Data Source=.\Express;AttachDBFilename=|DataDirectory|\MyDB.mdf;Integrated Security=true;User Instance=false"))
{
conn.Open();
using (SqlCommand updateCmd = conn.CreateCommand())
{
updateCmd.CommandText = "update T_Users Set ErrorTimes=0 where UserName=@UserName";//重置错误次数为0
updateCmd.Parameters.Add(new SqlParameter("UserName", txtUserName.Text));
updateCmd.ExecuteNonQuery();
}
}
}
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(@"Data Source=.\Express;AttachDBFilename=|DataDirectory|\MyDB.mdf;Integrated Security=true;User Instance=false"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from T_Users where UserName=@UN";
cmd.Parameters.Add(new SqlParameter("UN", txtUserName.Text));
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
int errorTimes = reader.GetInt32(reader.GetOrdinal("ErrorTimes"));
if (errorTimes > 3) //超过三次禁止登录
{
MessageBox.Show("登录次数过多,禁止登录");
return;
}
string dbPassword = reader.GetString(reader.GetOrdinal("Password"));
if (dbPassword == txtPassword.Text)
{
MessageBox.Show("登录成功 ");
ResetErrorTimes(); //登录成功后要重置错误次数
}
else
{
IncErrorTimes(); //累加错误次数
MessageBox.Show("登录失败");
}
}
else
{
MessageBox.Show("用户名不存在");
}
}
}
}
}
|
方法一:(先根据用户名查询对应的信息,再读取密码与输入密码进行判断)
最新推荐文章于 2021-02-16 06:51:24 发布