- namespace 登陆练习1
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void incErrorTimes()
- {
- using (SqlConnection conn = new SqlConnection(@"Data Source=./SQLEXPRESS;
- AttachDBFilename=D:/My Documents/Documents/Visual Studio 2010/Projects/登陆练习1/登陆练习1/MyDB.mdf;
- Integrated Security=True;User Instance=True"))
- {
- conn.Open();
- using (SqlCommand cmd = conn.CreateCommand())
- {
- cmd.CommandText = "update T_User Set ErrorTimes=ErrorTimes+1 where UserName=@UserName";
- cmd.Parameters.AddWithValue("UserName",txtUserName.Text);
- cmd.ExecuteNonQuery();
- }
- }
- }
- private void resetErrorTimes()
- {
- using (SqlConnection conn = new SqlConnection(@"Data Source=./SQLEXPRESS;
- AttachDBFilename=D:/My Documents/Documents/Visual Studio 2010/Projects/登陆练习1/登陆练习1/MyDB.mdf;
- Integrated Security=True;User Instance=True"))
- {
- conn.Open();
- using (SqlCommand cmd = conn.CreateCommand())
- {
- cmd.CommandText = "update T_User Set ErrorTimes=0 where UserName=@UserName";
- cmd.Parameters.AddWithValue("UserName", txtUserName.Text);
- cmd.ExecuteNonQuery();
- }
- }
- }
- private void button1_Click(object sender, EventArgs e)
- {
- using (SqlConnection conn = new SqlConnection(@"Data Source=./SQLEXPRESS;
- AttachDBFilename=D:/My Documents/Documents/Visual Studio 2010/Projects/登陆练习1/登陆练习1/MyDB.mdf;
- Integrated Security=True;User Instance=True"))
- {
- conn.Open();
- using (SqlCommand cmd = conn.CreateCommand())
- {
- cmd.CommandText = "select * from T_User where UserName=@UserName";
- cmd.Parameters.AddWithValue("UserName",txtUserName.Text);
- using (SqlDataReader reader = cmd.ExecuteReader())
- {
- if (reader.Read())
- {
- int errortimes = reader.GetInt32(reader.GetOrdinal("ErrorTimes"));
- if (errortimes > 3)
- {
- MessageBox.Show("密码错误次数过多,禁止登陆!");
- return;
- }
- else
- {
- string password = reader.GetString(reader.GetOrdinal("Password"));
- if(password==txtPassword.Text)
- {
- MessageBox.Show("用户登陆成功!");
- resetErrorTimes();
- }
- else
- {
- incErrorTimes();
- MessageBox.Show("密码错误!");
- }
- }
- }
- else
- {
- MessageBox.Show("用户名不存在!");
- }
- }
- }
- }
- }
- }
- }