1

I have a Table in my local database Ships(HistID,ShipName,ShipLength). I am polling the database for all ships with HistID == theme, but while(reader.Read()){} is never entered. Also, my Ships table has more than one row (saw this problem in another SO question) so I'm not sure why I cant store the results into List of Tuples. Executing the query alone in Visual Studio 2015 yields the correct results.

     public List<Tuple<String, int>> getHistoricalShipList(int theme)
        {
            List<Tuple<String, int>> list = new List<Tuple<string, int>>();

            using (db)
            {
                   cmd = new SqlCommand(@"Select ShipName, ShipLength from Ships Where HistID=@theme", db);
                   cmd.Parameters.AddWithValue("@theme", theme);

                db.Open();

                SqlDataReader reader = cmd.ExecuteReader();

                if (reader.HasRows) // always returning false
                {
                    //Loop through results
                    while (reader.Read())
                    {
                        String shipName = reader[0].ToString();
                        int shipLength = Convert.ToInt32(reader[1]);
                        list.Add(Tuple.Create(shipName, shipLength));
                    }
                }
                db.Close();
            }

            return list;
        }

EDIT:: removed the single quotes from the query as suggested, but still having the same issue.

4
  • What is the type of HistID column? Sounds like numeral based on it's name. You should always use parameterized queries by the way. This kind of string concatenations are open for SQL Injection attacks. Commented Feb 25, 2016 at 15:50
  • There is so many things going on in your code, that I don't know where to start. Check your using blocks. You have not enough and at least the one for db looks fishy. You should use parameters instead of string format for your query. And there is no point in having an if(hasRows) when you have a while loop around your read. Commented Feb 25, 2016 at 15:52
  • Use parametrized query, not string.Format. Does the generated query return any results outside your program? Commented Feb 25, 2016 at 15:52
  • Yes Vojtech, When I open up a Query editor in VS, the query returns what I need it to return. I am beginner, please excuse my terrible coding! Commented Feb 25, 2016 at 15:57

2 Answers 2

3

Your theme is of type int, and you are enclosing it in single quotes like it is a string value. Remove the quotes, but more importantly, use Parameters

cmd = new SqlCommand(string.Format(@"Select ShipName, ShipLength from Ships Where HistID={0}", theme), db);

Never use string concatenation/string format to build SQL statements, your code is prone to SQL injection.

cmd = new SqlCommand(@"Select ShipName, ShipLength from Ships Where HistID=@theme", db);
cmd.Parameters.AddWithValue("@theme", theme);
//Or more precise 
//cmd.Parameters.Add(new SqlParameter("@theme", SqlDbType.Int) {Value = theme});

The reason you are not getting any rows back is, that your field HistID is of numeric type and you are trying to compare it with a string value (by enclosing the value in single quote).

Sign up to request clarification or add additional context in comments.

5 Comments

AddWithValue? Ouchh.. :)
Oh no! Your right, I missed that. However, I updated that line and I'm still reader.Read() is still false. Updated OP with your correction.
Agreed w/everything except that this is the OP's actual problem; because of implicit conversion, the query would still work.
@SonerGönül There is nothing wrong with AddWithValue if you are using it on a non variable length or non ambiguous type. Sure, for strings and byte[] I would never use it, but for a int, there is nothing wrong with that.
@ScottChamberlain Yes, this isn't a problem in this case but as a general recommendation, specially explicitly specifying DbType, makes code much more readable and understandable in my opinion.
1

Remove HasRows check and just use the .Read while loop; there's various bug reports on HasRows not being entirely accurate in some cases.

Other than that, it's likely you're making a mistake somewhere. Either theme isn't what you expect it to be, or some environment error like hitting the wrong database.

1 Comment

I hate it when I blunder this bad. Theme was being passed in as 0 always, which doesn't exist in my DB. I hard-coded a 1 in (which exists) and the problem is solved. THANK YOU!!

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.