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!

8
  • What type is Id in the database? Is it something other than an int? Commented Nov 29, 2014 at 2:34
  • @DavidL It is stored as an Integer in the database. Commented Nov 29, 2014 at 2:35
  • @Giri all you need is int result = cmd.ExecuteScalar(); then check if result is null Commented Nov 29, 2014 at 2: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? Commented Nov 29, 2014 at 2: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 Commented Nov 29, 2014 at 2:43

1 Answer 1

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());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.