1

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!

Community
  • 1
  • 1
  • What type is Id in the database? Is it something other than an int? – David L Nov 29 '14 at 02:34
  • @DavidL It is stored as an `Integer` in the database. –  Nov 29 '14 at 02:35
  • @Giri all you need is `int result = cmd.ExecuteScalar();` then check if result is null – meda Nov 29 '14 at 02:37
  • @meda Actually, that is what I tried initially. However like I mentioned above, I get the same error. Does this suggest there may be an issue with my database? –  Nov 29 '14 at 02:41
  • 1
    @Giri is this piece of code inside of a try catch? you should place a breakpoint right on execute() and step through the code you will see the issue – meda Nov 29 '14 at 02:43
  • What type and value is obj at return (T)obj if you place a breakpoint at that line? – David L Nov 29 '14 at 02:47
  • @DavidL Ohhh it is a `long`.. –  Nov 29 '14 at 02:54
  • There you go :). It's not actually an int and you can't cast a long to an int. – David L Nov 29 '14 at 02:55

1 Answers1

1

Per the comments, you cannot cast a long to an int. By passing in long, you will not have a cast exception.

long result = ConvertFromDBVal<long>(cmd.ExecuteScalar());
David L
  • 32,885
  • 8
  • 62
  • 93