I've got this code:
private int GetCombinedRankRank(int combinedRankValue)
{
try
{
conn = new MySqlConnection(connstr);
conn.Open();
try
{
DataTable dtStates = new DataTable();
MySqlCommand comm = conn.CreateCommand();
comm.CommandText = "SELECT COUNT(states_id) "+
"FROM states "+
"WHERE combinedRank < @combinedRankValue";
comm.Parameters.AddWithValue("@combinedRankValue", combinedRankValue);
return (int)comm.ExecuteScalar();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
throw;
}
}
finally
{
conn.Close();
}
}
...which fails on the line:
return (int)comm.ExecuteScalar();
...with "Specified cast is not valid" -- Yet the same SQL works in Database Workbench:
The SQL returns an int. The data type of the combinedRank column in the Table is Integer. I am casting that value to an int. How can that be an invalid cast?
This is something I had encountered earlier so I can shed my two cents on it:
The
comm.ExecuteScalar()
will returnlong
in case ofMySqlCommand
. You can check if this is true by printing thetypeof cmd.ExecuteScalar()
. It should returnlong
. If so, correct way to typecast would be the following:This should avoid any data loss. However, when I look at the examples given by mysql connector (https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-sql-command.html), they are using the following:
They use
Convert.ToInt32
and also check if the object is null which I feel is correct way to handle the situation. Maybe change it tolong
if the returntype islong
: