【问题标题】:Casting Result from SQL Query - System.InvalidCastException来自 SQL 查询的转换结果 - System.InvalidCastException
【发布时间】:2014-11-29 02:30:05
【问题描述】:

我正在尝试存储select 查询的结果。返回的值作为integer 存储在Sqlite 中。

我决定试试这个答案中提出的内容:https://stackoverflow.com/a/870771

我的代码目前是:

 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;
        }
    }

但是,我收到错误消息:

System.InvalidCastException 在这一行:

return (T)obj;

如果我只是尝试将cmd.ExecuteScalar()) 的结果存储为int,我会得到同样的错误。

我必须承认我并不完全理解这个功能,所以如果有人也能对此有所了解,我将不胜感激!

【问题讨论】:

  • 数据库中的Id是什么类型?它不是 int 吗?
  • @DavidL 在数据库中存储为Integer
  • @Giri 你只需要int result = cmd.ExecuteScalar(); 然后检查结果是否为空
  • @meda 实际上,这就是我最初尝试的方法。但是,就像我上面提到的,我得到了同样的错误。这是否表明我的数据库可能存在问题?
  • @Giri 这段代码是在 try catch 中吗?您应该在 execute() 上放置一个断点并单步执行您将看到问题的代码

标签: c# sql sqlite casting


【解决方案1】:

根据 cmets,您不能将 long 转换为 int。通过 long 传递,您将不会出现强制转换异常。

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

【讨论】:

    猜你喜欢
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多