要求:
页面:
数据库设定
主程序
using System; using System.Data.SqlClient; using System.Windows.Forms; namespace Test01 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void BtOK_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection("server=PC201609230944\\SQL2005;database=HeiMaBlog;user=sa;pwd=123456"); SqlCommand cmd = new SqlCommand("select *,datediff(minute,LastErrTime,GETDATE()) from UserInfo where UserName=@UserName", conn); cmd.Parameters.Add(new SqlParameter("@UserName", TxName.Text.Trim())); conn.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { dr.Read();////不管dr取到多少条数据,只取出前面第一行(调用一次read,就会读取一行,也只读取一行) if (dr.GetInt32(5) < 15) { MessageBox.Show("时间未到,请稍后重试!!"); return; } if (dr[2].ToString() == TxPwd.Text.Trim()) { MessageBox.Show("登录成功!!"); UserInfo.ReSetErrTimes(dr.GetInt32(0));//登录成功后,就重置错误时间 } else { //如果密码不正确!! MessageBox.Show("登录失败,密码错误"); UserInfo.UpDateErrTimes(dr.GetInt32(0)); // 错误三次就更新错误时间 if (dr.GetInt32(3) + 1 == 3) { UserInfo.UpDateLastErrTime(dr.GetInt32(0)); UserInfo.ReSetErrTimes(dr.GetInt32(0)); } } } else { MessageBox.Show("该用户不存在!!!"); } } } }
辅助
using System.Data.SqlClient; namespace Test01 { class UserInfo { /// <summary> /// 更新错误时间!! /// </summary> /// <param name="id"></param> /// <returns></returns> public static int UpDateErrTimes(int id) { using (SqlConnection conn = new SqlConnection("server=PC201609230944\\SQL2005;database=HeiMaBlog;user=sa;pwd=123456")) { using (SqlCommand cmd = new SqlCommand("update UserInfo set ErrTimes=ErrTimes+1 where id=" + id, conn)) { conn.Open(); return cmd.ExecuteNonQuery(); } } } /// <summary> /// 重置错误时间 /// </summary> /// <param name="id"></param> /// <returns></returns> public static int ReSetErrTimes(int id) { using (SqlConnection conn = new SqlConnection("server=PC201609230944\\SQL2005;database=HeiMaBlog;user=sa;pwd=123456")) { using (SqlCommand cmd = new SqlCommand("update UserInfo set ErrTimes=0 where id=" + id, conn)) { conn.Open(); return cmd.ExecuteNonQuery(); } } } /// <summary> /// 更新3次错误的输入时间 /// </summary> /// <param name="id"></param> /// <returns></returns> public static int UpDateLastErrTime(int id) { using (SqlConnection conn = new SqlConnection("server=PC201609230944\\SQL2005;database=HeiMaBlog;user=sa;pwd=123456")) { using (SqlCommand cmd = new SqlCommand("update UserInfo set LastErrTime = getDate() where id= " + id, conn)) { conn.Open(); return cmd.ExecuteNonQuery(); } } } } }
注意:SqlDataReader的Read将数据读取出来到本地而已,对读取出来的本地数据进行整改对数据库没有啥作用。