说明:登录失败3次,15分钟后才能登录
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UeerLogin
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnLogin_Click(object sender, EventArgs e)
{
//操作数据库
string id = txtUserName.Text.Trim();
string pwd = txtPwd.Text.Trim();
string strSQL = "select Id, Name, Pwd, Phone, Email, ErrorTimes, LastErrorTime,DATEDIFF(minute,LastErrorTime,getdate()) as ErrorMinute from UserInfo where Id =" + id;
if (GetUserInfo(strSQL))
{
if (user.ErrorTimes>=3&&user.ErrorMinute<15 )
{
MessageBox.Show("登录失败!用户被锁");
return;
}
if (pwd.Trim() == user.Pwd.Trim())
{
//执行更新操作---ErrorTimes=0
strSQL = "Update UserInfo set ErrorTimes=0 where Id =" + id;
UpdateUserInfo(strSQL);
MessageBox.Show("登录成功");
}
else
{
//执行更新操作---ErrorTime+1,LastErrorTime
user.ErrorTimes = user.ErrorTimes + 1;
strSQL = string.Format("Update UserInfo set ErrorTimes= {0},LastErrorTime='{1}' where Id ={2}", user.ErrorTimes,DateTime.Now, user.Id);
// strSQL = string.Format("Update UserInfo set ErrorTimes= {0},LastErrorTime={1}", user.ErrorTimes, DateTime.Now);
UpdateUserInfo(strSQL);
MessageBox.Show("登录失败!用户密码错误.错误次数"+user.ErrorTimes);
}
}
else
{
MessageBox.Show("登录失败!用户不存在");
}
}
public UserInfo user = new UserInfo();
public bool GetUserInfo(string strSQL)
{
//创建连接字符串
string connstr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
//连接数据库
using (SqlConnection conn = new SqlConnection(connstr))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(strSQL,conn))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
user.Id = Convert.ToInt32(reader["Id"].ToString());
user.Pwd = reader["Pwd"].ToString();
//数据库中设置不能为空,默认值为0,不然转换会出错
user.ErrorTimes =Convert.ToInt32(reader["ErrorTimes"].ToString());
user.ErrorMinute =Convert.ToInt32(reader["ErrorMinute"].ToString());
return true;
}
}
}
}
return false;
}
public bool UpdateUserInfo(string strSQL)
{
//创建连接字符串
string connstr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
//连接数据库
using (SqlConnection conn = new SqlConnection(connstr))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(strSQL, conn))
{
if (cmd.ExecuteNonQuery()>0)
{
return true;
}
}
}
return false;
}
}
}
注:参数格式化
cmd.CommandText=@"select count(*) from UserInfo where UserName = @UserName and UserPwd = @UserPwd";
cmd.Parameters.Add("@UserName",txtUserName.Text);
cmd.Parameters.AddWithValue("@demo",0);