Home > other >  How to check SqlParameter is true with If
How to check SqlParameter is true with If

Time:11-09

I want to check sqlparameter is true on if statements like this;

        string sql1 = "SELECT * FROM users WHERE mail=@mail and passwd is null";
        string sql2 = "SELECT * FROM users WHERE mail=@mail and passwd=@password";
        SqlParameter prm1 = new SqlParameter("mail", txtMail.Text.Trim());
        SqlParameter prm2 = new SqlParameter("password", txtPassword.Text.Trim());
        if (sql1 == true)
        {
           
            MessageBox.Show("yes");
        }
        else if (sql2 == true)
        {
            MessageBox.Show("yes2");
        }
        {
            MessageBox.Show("no");
        }

CodePudding user response:

It's rather unclear what you are trying to do, but it looks like you might want code like this:

const string query = @"
SELECT CASE WHEN passwdHash is null THEN 1 ELSE 2 END
FROM users
WHERE mail = @mail and (passwdHash is null OR passwdHash = @passwdHash);
";
using (var conn = new SqlConnection(yourConnString))
using (var comm = new SqlCommand(query, conn))
{
    comm.Parameters.Add("@mail", SqlDbType.VarChar, 200).Value = txtMail.Text.Trim();
    comm.Parameters.Add("@passwordHash", SqlDbType.Binary, 32) = SaltAndHashPassword(txtPassword.Text.Trim());
    conn.Open();
    var result = comm.ExecuteScalar() as int?;
    conn.Close();
    if (result == 1)
    {
        MessageBox.Show("yes");
    }
    else if (result == 2)
    {
        MessageBox.Show("yes2");
    }
    else
    {
        MessageBox.Show("no");
    }
}

Note the following

  • using blocks on all Sql objects
  • Specify parameter types and lengths explicitly
  • Hash the password and compare that instead
  • Don't select *, just pass back a single column with a result
  • Close the connection before blocking with a MessageBox
  • Related