使用C#

时间:2017-08-27 09:14:19

标签: c# sql-server-2012

这是我的程序,我需要验证用户名或密码是否已经存在,但如果我添加另一个using语句进行验证,它仍会通过数据库。我应该如何使用带有sql语句的IF ELSE语句,例如(“@ username”== _f3txtuser.text)

    private void _F3Register_Click(object sender, EventArgs e)
    {


        if (_F3txtUser.Text == "" || _F3txtPass.Text == "")
            MessageBox.Show("Please Fill The Missing Informations");
        else if (_F3txtPass.Text != _F3txtCheckPass.Text)
            MessageBox.Show("Password Do Not Match");

        else if (("@USERNAME" == _F3txtUser) || ("@PASSWORD" == _F3txtPass))
            MessageBox.Show("Username or Password already Exists");

        else
        {
            using (SqlConnection _sqlcon = new SqlConnection(connectionstring)) //Database Connection
            {
                _sqlcon.Open();


                String query2 = "Insert into LOGINFORM(USERNAME, PASSWORD, FNAME, LNAME, AGE) values(@USERNAME, @PASSWORD, @FNAME, @LNAME, @AGE)"; // Database Command for Insertion

                using (SqlCommand _sqlcmd = new SqlCommand(query2, _sqlcon)) //using database connection and command in one method
                {
                    _sqlcmd.Parameters.AddWithValue("@USERNAME", _F3txtUser.Text.Trim());
                    _sqlcmd.Parameters.AddWithValue("@PASSWORD", _F3txtPass.Text.Trim());
                    _sqlcmd.Parameters.AddWithValue("@FNAME", _txtFN.Text.Trim());
                    _sqlcmd.Parameters.AddWithValue("@LNAME", _txtLN.Text.Trim());
                    _sqlcmd.Parameters.AddWithValue("@AGE", _txtAge.Text.Trim());
                    _sqlcmd.ExecuteNonQuery();
                }
                MessageBox.Show("Registration Successfull");
                Clear();

            }
        }
    }
    void Clear()
    {
        _F3txtUser.Clear();
        _F3txtPass.Clear();
        _txtFN.Clear();
        _txtLN.Clear();
        _txtAge.Clear();
        _F3txtCheckPass.Clear();
    }
}

}

1 个答案:

答案 0 :(得分:1)

您可以使用以下方法:

    private bool UserNameOrPasswordExists(string userName, string password)
    {
        using (SqlConnection conn = new SqlConnection("your connection string"))
        {
            conn.Open();
            var query = "Select * from LOGINFORM where USERNAME='@USERNAME' or PASSWORD='@PASSWORD'";
            using (SqlCommand comm = new SqlCommand(query, conn))
            {
                comm.Parameters.AddWithValue("@USERNAME", userName);
                comm.Parameters.AddWithValue("@PASSWORD", password);
                var result = comm.ExecuteNonQuery();
                return result > 0;
            }
        }
    }

然后用这个替换第三个if else:

    else if (UserNameOrPasswordExists(_F3txtUser, _F3txtPass))
        MessageBox.Show("Username or Password already Exists");