Why does my datareader always return false when they are valid rows?

jackie11

New member
Joined
Mar 27, 2015
Messages
3
Programming Experience
1-3
Hi there

I have the following method;

C#:
public static Boolean CheckIFPackageExists(string id)
        {

            OleDbConnection myConnection = GetConnection();
            string myQuery = "SELECT * FROM Package WHERE Email =" + id;
            OleDbCommand command = new OleDbCommand(myQuery, myConnection);

            try
            {
                myConnection.Open();
                OleDbDataReader myReader = command.ExecuteReader();
                return myReader.Read();
                
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception in DBHandler", ex);
                return false;
            }
            finally
            {
                myConnection.Close();

            } 
        }

But I have loads of rows with the id being passed in to this method, but it always returns false when it should return true.

Does anyone have any idea why?

Many thanks
 
Have you confirmed that it's hitting the `return` statement in the `try` block and not the one in the `catch` block? It seems odd that you'd be using a parameter named `id` to compare to a column named Email. Given that the column is named Email, I would expect it to be a text column, in which case you'd have to compare it to a text value, which you're not. If you use a text literal then it must be wrapped in single quotes. You shouldn't be using a literal in that situation though. You should be using a parameter. To learn why and how, follow the Blog link in my signature below and check out my post on Parameters In ADO.NET.

Apart from that, it is wrong to call Read in that situation. Why read a record that you're never going to use? It would be more appropriate to return the value of the HasRows property.
 
Try to put single quotes around the id like this

string myQuery = "SELECT * FROM Package WHERE Email = ' " + id + " ' ";
 
Back
Top Bottom