I am trying to store the result of a select
query. The value being returned is stored as an integer
in Sqlite
.
I decided to try what was presented in this answer: https://stackoverflow.com/a/870771
My code is currently:
cmd.CommandText = "SELECT id FROM TVShows WHERE id = @id";
cmd.Parameters.Add(new SQLiteParameter("@id", id));
conn.Open();
object result = ConvertFromDBVal<int>(cmd.ExecuteScalar());
private T ConvertFromDBVal<T>(object obj)
{
if (obj == null || obj == DBNull.Value)
{
return default(T); // returns the default value for the type
}
else
{
return (T)obj;
}
}
However, I am receiving the error:
System.InvalidCastException
at this line:
return (T)obj;
If I simply try and store the result of cmd.ExecuteScalar())
as an int
, I get the same error.
I must admit I don't completely understand this function and so if someone could shed some light on that as well, I'd greatly appreciate it!