登录错误次数限制及参数化传递防止sql注入

  1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Windows.Forms;
9 using System.Configuration;
10 using System.Data.SqlClient;
11
12 namespace 复习登录
13 {
14 public partial class login : Form
15 {
16 public login()
17 {
18 InitializeComponent();
19 }
20 string str = ConfigurationManager.ConnectionStrings["sqlserver2008"].ConnectionString;
21 DateTime dt1;
22 private void btn_login_Click(object sender, EventArgs e)
23 {
24 using(SqlConnection cnn=new SqlConnection(str))
25 {
26 using (SqlCommand cmd=cnn.CreateCommand())
27 {
28 cmd.CommandText = "select * from T_User where username=@username";
29 cmd.Parameters.AddWithValue("@username", txt_username.Text);
30 cnn.Open();
31 using (SqlDataReader reader = cmd.ExecuteReader())
32 {
33 if (reader.Read())
34 {
35 int Error = Convert.ToInt32(reader["Error"].ToString());
36 if (Error >= 3)
37 {
38
39 string sqltime = reader["Errortime"].ToString();
40 dt1 = DateTime.Parse(sqltime);
41 DateTime dt2 = DateTime.Now;
42 TimeSpan ts = dt2 - dt1;
43 if (ts.TotalMinutes < 5)
44 {
45 MessageBox.Show("对不起,你已经输入3次连续错误密码,系统已经将账户冻结,请在五分钟后再试");
46 return;
47 }
48 else
49 {
50 clearerror();
51 }
52
53 }
54 string sqlpassword = reader["Password"].ToString();
55 if (sqlpassword == txt_password.Text)
56 {
57 clearerror();
58 if (txt_username.Text.ToUpper() == "ADMIN")
59 {
60 this.Hide();
61 main m = new main();
62 m.Show();
63 }
64 else
65 {
66 MessageBox.Show("登录成功");
67 }
68 }
69 else
70 {
71 MessageBox.Show("密码错误");
72 adderror();
73 }
74 }
75 else
76 {
77 MessageBox.Show("用户名不存在");
78 }
79
80 }
81 }
82 }
83 }
84
85 private void adderror()
86 {
87 dt1 = DateTime.Now;
88 using (SqlConnection cnn=new SqlConnection(str))
89 {
90 using (SqlCommand cmd=cnn.CreateCommand())
91 {
92 cnn.Open();
93 cmd.CommandText = "update T_User set Error=Error+1,Errortime=@Errortime where username=@username";
94 cmd.Parameters.AddWithValue("@Errortime", dt1);
95 cmd.Parameters.AddWithValue("@username", txt_username.Text);
96 cmd.ExecuteNonQuery();
97
98 }
99 }
100 }
101 private void clearerror()
102 {
103 using (SqlConnection cnn=new SqlConnection(str))
104 {
105 using (SqlCommand cmd=cnn.CreateCommand())
106 {
107 cnn.Open();
108 cmd.CommandText = "update T_User set Error=0 where username=@username";
109 cmd.Parameters.Add(new SqlParameter("username", txt_username.Text));
110 cmd.ExecuteNonQuery();
111 }
112 }
113 }
114 }
115 }

 

posted @ 2012-02-22 18:01  SOD_QWER  阅读(810)  评论(0编辑  收藏  举报