C# MySQL Order By Returns 1

I'm trying to get the last row of a table using C# but it doesn't seem to be working, this is my code:

MySqlConnection cnnGetID = new MySqlConnection(Global.connectionString);

cmd = "SELECT ContactID FROM Contacten ORDER BY ContactID DESC LIMIT 1";
MySqlCommand cmdGetID = new MySqlCommand(cmd, cnnGetID);

cnnGetID.Open();
string contactID = cmdGetID.ExecuteNonQuery().ToString();
MessageBox.Show(contactID);

cnnGetID.Close();

The value this returns is -1 while it should be returning 59.

The strange thing is is that when I run this command in phpmyadmin I DO get 59.

Any ideas on why C# is not returning the correct value but phpmyadmin is?

EDIT: problem solved, should've uses ExecuteScalar(). Looks like I've been staring at my monitor for a bit too long...

Jon Skeet
people
quotationmark

The value this returns is -1 while it should be returning 59.

No, it's behaving exactly as documented by IDbCommand.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.

You're using a SELECT statement - a query. So instead of executing ExecuteNonQuery, you should be using ExecuteQuery and iterating over the results, or ExecuteScalar, given that you know you'll have a single result:

string contactID = cmdGetID.ExecuteScalar().ToString();

people

See more on this question at Stackoverflow