如何使我的登录表单面向对象

时间:2018-09-12 02:59:25

标签: c# oop

我的问题是我不知道如何从表单登录名调用班级的文本框和按钮。因此,我决定将代码放入btnLogin事件中。我怎样才能使我的代码符合风格?

 private void btnLogin_Click(object sender, EventArgs e)
        {
            int count = 0;
            Connection connection = new Connection();
            string sql = "SELECT * FROM tbl_Account WHERE Username='" + txtUserName.Text + "' and Password='" + txtPassword.Text + "'";
            MySqlConnection conn = new MySqlConnection(connection.ConnectionString);
            MySqlCommand cmd = new MySqlCommand(sql, conn);
            conn.Open();
            MySqlDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                count++;
            }
            if (count == 1)
            {
                MessageBox.Show("Login Successfully!");
                this.Hide();
                main.showMeForm4(this);
            }
            else
            {
                txtPassword.Focus();
                MessageBox.Show("Username or Password Is Incorrect");
                txtUserName.Text = "";
                txtPassword.Text = "";

            }
            conn.Close();
        }

1 个答案:

答案 0 :(得分:0)

将您的业务逻辑放在单独的类中: 不要连接SQL查询(SQL Injections)。 BusinessLogic类

public bool Authorize(string userName, string userPassword)
       {
            Connection connection = new Connection();
            string sql = "SELECT Count(*) FROM tbl_Account WHERE Username=@userName and Password=@userPassword";
            MySqlConnection conn = new MySqlConnection(connection.ConnectionString);
            MySqlCommand cmd = new MySqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("@userName",userName);
            cmd.Parameters.AddWithValue("@userPassword",userPassword);
            int count = 0;
            try
            {
               conn.Open();
               int count = int.TryParse(cmd.ExecuteScalar().ToString());                
            }
            finally
            {
              con.Close();
            }
            return count==1;
       }

调用:

BusinessLogic businessLogic = new BusinessLogic();

private void btnLogin_Click(object sender, EventArgs e)
        {
            if (businessLogic.Authorize(txtUserName.Text, txtPassword.Text)
            {
                 MessageBox.Show("Login Successfully!");
                 this.Hide();
                 main.showMeForm4(this);
            }
            else
            {
                 txtPassword.Focus();
                MessageBox.Show("Username or Password Is Incorrect");
                txtUserName.Text = "";
                txtPassword.Text = "";
            }
        }
相关问题