1

I want to check if my query returns any value or not and write the remaining logic accordingly.

SqlCommand myCommand = new SqlCommand("Select * from phc.userbase where [user]='@Username' and [password]='@password'", myConnection);

I want to know this command returns null or not. I tried

myReader = myCommand.ExecuteReader();
bool rd = myReader.Read();

if rd==false

but I can't get it working. Any ideas?

Here are my parameters:

SqlParameter myParam = new SqlParameter("@Username", SqlDbType.VarChar, 25);
myParam.Value = usr;

SqlParameter myParam2 = new SqlParameter("@password", SqlDbType.VarChar, 25);
myParam2.Value = pass;
5
  • 2
    So... you're storing passwords as plain text in the database? That is not good. Also, it isn't clear if you are parameterizing that correctly - the parameters should probably not be in quotes. Commented Mar 15, 2012 at 8:10
  • @MarcGravell this is just a dummy demo.I plan to use MD5 encryption later. Commented Mar 15, 2012 at 8:12
  • To clarify: at the moment you are searching for a user called '@Username' with a password of '@Password' - which is very different to checking whether they have a username the same as the value of the parameter @Username. I bet that query always returns zero rows, right? Commented Mar 15, 2012 at 8:14
  • @MarcGravell yep.Been stuck on this for hours.Any ideas? Commented Mar 15, 2012 at 8:22
  • yes; as I've already mentioned twice: take the quotes away. The quotes are wrong here. Should be [user] = @Username and [password] = @password - look - no quotes! Commented Mar 15, 2012 at 8:24

2 Answers 2

2

It depends what you mean by null here; do you mean "no rows" ? If so:

using(var myReader = myCommand.ExecuteReader()) {
    if(myReader.Read()) {
      // at least 1 row; can now check columns
    } else {
      // no rows
    }
}

To be honest, though, you could probably change that to SELECT 1 ... and use ExecuteScalar - much less bother.

In this case, though, it is probably easier to just SELECT 1 ...rest of query... and use:

object value = myCommand.ExecuteScalar();
if(value != null) { ... got a row ...}
Sign up to request clarification or add additional context in comments.

1 Comment

Can you point me in the right direction with the execute scalar
2

use SqlDataReader.HasRows()

if (myReader.HasRows())
{
    // Do something
}

2 Comments

I just want to know if my query returns a value or not.forgive me if i'm wrong but,wouldn't this check for values inside a table?
@deception1 your query has a filter; it will only HasRows() if your query finds a match

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.