简体   繁体   English

SQL查询的转换结果-System.InvalidCastException

[英]Casting Result from SQL Query - System.InvalidCastException

I am trying to store the result of a select query. 我正在尝试存储select查询的结果。 The value being returned is stored as an integer in Sqlite . 返回的值在Sqlite存储为integer

I decided to try what was presented in this answer: https://stackoverflow.com/a/870771 我决定尝试此答案中介绍的内容: 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: System.InvalidCastException在此行:

return (T)obj;

If I simply try and store the result of cmd.ExecuteScalar()) as an int , I get the same error. 如果我只是尝试将cmd.ExecuteScalar())的结果存储为int ,则会遇到相同的错误。

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! 我必须承认我不完全了解此功能,因此,如果有人也能对此有所了解,我将不胜感激!

Per the comments, you cannot cast a long to an int. 根据注释,不能将long转换为int。 By passing in long, you will not have a cast exception. 通过长时间传递,您将不会有强制转换异常。

long result = ConvertFromDBVal<long>(cmd.ExecuteScalar());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM