概述:輸錯三次禁止登陸,15分鐘後才能繼續。圖示:Form1代碼:using System;using System.Configuration;using System.Data.SqlClient;using System.Windows.Forms;namespace 登錄驗證項目{ publ... ...
概述:輸錯三次禁止登陸,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]