---------------------- Windows Phone 7手机开发、.Net培训、期待与您交流! ----------------------
namespace winform1
{ public partial class Form1 : Form { public Form1() { InitializeComponent(); }//将错误次数变为零
public void ResetErrorTimes() { using (SqlConnection conn = new SqlConnection(@"Data Source=.\sqlexpress;attachDBFilename=|DataDirectory|\Database2.mdf;Integrated Security=True;User Instance=True")) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = "update T_Users set ErrorTimes=0 where UserName=@UserName"; cmd.Parameters.Add(new SqlParameter("UserName", textBox1.Text)); cmd.ExecuteNonQuery();}
} }//将错误次数加一
public void IncErrorTimes()
{ using (SqlConnection conn = new SqlConnection(@"Data Source=.\sqlexpress;attachDBFilename=|DataDirectory|\Database2.mdf;Integrated Security=True;User Instance=True")) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = "update T_Users set ErrorTimes=ErrorTimes+1 where UserName=@UserName"; cmd.Parameters.Add(new SqlParameter("UserName", textBox1.Text)); cmd.ExecuteNonQuery();}
} } private void button1_Click(object sender, EventArgs e) { using (SqlConnection conn = new SqlConnection(@"Data Source=.\sqlexpress;attachDBFilename=|DataDirectory|\Database2.mdf;Integrated Security=True;User Instance=True")) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = "select * from T_Users where UserName=@UserName";// cmd.Parameters.Add(new SqlParameter("UserName", textBox1.Text)); using (SqlDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { int errorTimes = reader.GetInt32(reader.GetOrdinal("ErrorTimes"));//防sql注入漏洞攻击,参数化查询 if (errorTimes > 3) { MessageBox.Show("登录错误次数太多,禁止登录"); return; } string dbpassword = reader.GetString(reader.GetOrdinal("PassWord")); if (dbpassword == textBox2.Text) { MessageBox.Show("登陆成功"); ResetErrorTimes(); } else { IncErrorTimes(); MessageBox.Show("登录失败"); } } else { MessageBox.Show("用户名不存在"); } } } } } } }
相关截图:
登录代码很多,所以写了两个函数,将部分功能进行封装,然后调用,这样能让函数主体更加清晰明了。
防sql注入漏洞攻击,用参数化查询的方式能使程序更加安全。
---------------------- Windows Phone 7手机开发、.Net培训、期待与您交流! ---------------------- 详细请查看:http://net.itheima.com/