WinForm登录验证
概述:输错三次禁止登陆,15分钟后才能继续。
图示:
Form1代码:
using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace 登录验证项目
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//连接数据库
//将连接字符串写入配置文件中 string connStr = "sever=.;uid=sa;pwd=123456;database=demo";
这部分写在配置文件中
//<connectionStrings>
// <add name="SqlConn" connectionString="server=.;uid=sa;pwd=123456;database=LoginBlock"/>
//</connectionStrings>
//条添加引用引入configuration命名空间
string connStr = ConfigurationManager.ConnectionStrings["SqlConn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
//select 查询语句str
string str = @"SELECT [Uid]
,[Unm]
,[Pwd]
,[ErrorDate]
,[ErrorTimes]
FROM [Login_Block]
WHERE Unm='" + textBox1.Text.Trim()
+ "' and Pwd='" + textBox2.Text.Trim() + "' ";
cmd.CommandText = str;
// bool ishasdata=false;
//这里创建Login对象
Login login = null;
using (SqlDataReader reader = cmd.ExecuteReader())
{//判断是否有数据
#region MyRegion
//if (!reader.hasrows)
//{
// //修改错误时间,错误次数
//}
#endregion
#region MyRegion
if (reader.HasRows)
{
reader.Read();
}
#endregion
if (reader.Read())
{
login = new Login();
login.Uid = int.Parse(reader["Uid"].ToString());
login.Pwd = reader["Pwd"].ToString();
login.ErrorTimes = int.Parse(reader["ErrorTimes"].ToString());
login.Errordata = DateTime.Parse(reader["Errordate"].ToString());
}
// ishasdata = reader.HasRows;
}//花括号执行结束之前reader对象一直占用conn对象
if (login == null/*!ishasdata*/)
{
//修改 错误时间,错误次数 where UserName=txtUserName.Text
cmd.CommandText =
"update Login_Block set Errordate=getdate(), ErrorTimes=ErrorTimes+1 where Unm='" +
textBox1.Text.Trim() + "'";
cmd.ExecuteNonQuery();
//MessageBox.Show("用户名密码Error");
return;
}
//执行有数据的过程
if (login.ErrorTimes < 3 || DateTime.Now.Subtract(login.Errordata).Minutes > 15)
{
MessageBox.Show("登录成功!!");
cmd.CommandText = "update Login_Block set ErrorTimes=0,Errordate=getdate() where Uid=" + login.Uid;
cmd.ExecuteNonQuery();
}
else
{
MessageBox.Show("登录失败!账号被锁定");
}
}
}
}
}
}
Login类:
using System;
namespace 登录验证项目
{
public class Login
{
//[Uid],[Pwd],[ErrorTimes],[Errordata]
public int Uid { get; set; }
public string Unm { get; set; }
public string Pwd { get; set; }
public int ErrorTimes { get; set; }
public DateTime Errordata { get; set; }
}
}
数据库:
表:Login_Block
字段:
[Uid]
[Unm]
[Pwd]
[ErrorDate]
[ErrorTimes]