I have a SQL query which returns only one field - an ID of type INT.
And I have to use it as integer in C# code.
Which way is faster and uses less memory?
if ((Int32)cmd.ExecuteScalar () ** 1) //en esta parece qu esta el error pero no lo veo
{
Response.Redirect("Default.aspx");
}
else
{
Response.Redirect("error.htm") ;
}
If you expect the command to return null, you should keep in mind that database null (DBNull) is not the same as .NET null. So, conversion of DBNull to int? would fail.
I'd suggest the following:
object result = command.ExecuteScalar();
int? id = (int?)(!Convert.IsDBNull(result) ? result : null);
The latter. Convert.ToInt32()
is also an option.
int Result = int.Parse(Command.ExecuteScalar().ToString());
will work in C#.
Use id.HasValue for maximum Nullable Type cool-factor!
If none of the above works (especially for users who are battling with MySQL) why don't you try the following?
int id = Convert.ToInt32(cmd.ExecuteScalar().ToString());