views:

32

answers:

1
MySqlCommand checkUsername = conn.CreateCommand();
checkUsername.CommandText = "SELECT COUNT(*) FROM users WHERE username='admin'";
MessageBox.Show("The count is " + checkUsername.ExecuteNonQuery());

There is more code where this "count" is actually being used, but it was not working correctly so I made this little message box pop up to show what number I was actually receiving. When I go phpmyadmin and do a direct SQL word for word (I copy/pasted) it has no issues and gives the correct number of times the username exists. However, every time in my program (C#, using VS2010) it gives me -1, whether the name doesn't exist, or I have it in their 5 times.

I'm thinking it must be something to do with the way C# formats the number it is getting back, but I'm not really sure how to correct it.

I've also read up on using EXISTS for this instead of COUNT(*), but I couldn't get that to work at all, it gave me syntax errors every time.

+3  A: 

Why are you calling ExecuteNonQuery when it is a query?

Use ExecuteScalar to execute a query which will give a single result.

It's quite right for ExecuteNonQuery to return -1. From the docs of DbCommand.ExecuteNonQuery:

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is -1.

Jon Skeet
I'm honestly not sure. From what I read I thought ExecuteNonQuery, but this is my first time using MySQL. I've been working on this on and off all day, and this is the only thing that has stumped me to the point where I just can't figure it out. It took me 2-3 hours just to get a connection made between my program and the server the database is on :( I did try switching it to scalar, but it is messing my if statement up now, saying "Operator '<' cannot be applied to operands of type 'object' and 'int'
zack
@zack: Well yes... that's because ExecuteScalar is declared to return `object`. You'll have to cast the result to `int` or `long`.
Jon Skeet
Thanks Jon it works perfectly now. 2 hours I've spent on this, and you fix it in less than 15 minutes!
zack
@zack: Well, the key is in reading the documentation and taking note of the method names :)
Jon Skeet