为什么我得到"无效的演员异常"用这个SQLite代码?

时间:2014-11-05 23:15:30

标签: c# sqlite casting windows-ce executescalar

我已经有了这个代码来从SQLite表中获取计数:

internal static bool TableExistsAndIsNotEmpty(string tableName)
{
    int count;
    string qry = String.Format("SELECT COUNT(*) FROM {0}", tableName);
    using (SQLiteConnection con = new SQLiteConnection(HHSUtils.GetDBConnection()))
    {
        con.Open();
        SQLiteCommand cmd = new SQLiteCommand(qry, con);
        count = (int)cmd.ExecuteScalar();
    }
    return count > 0;
}

当它运行时,我得到“无效的强制转换

很明显,从查询返回的值是一个int,也就是说记录的数量(当我运行查询时,我得到“2”,即“SELECT COUNT(*)FROM WorkTables”in Sqlite浏览器)。

那么在这里被无效投射的是什么?

作为一种旁注,我知道最好使用查询参数,我在Windows商店应用程序[How can I use SQLite query parameters in a WinRT app?中找到了如何执行此操作,但不知道如何执行此操作在一个旧的(Windows窗体/ Windows CE)应用程序。

我认为会是这样的:

string qry = "SELECT COUNT(*) FROM ?";
using (SQLiteConnection con = new SQLiteConnection(HHSUtils.GetDBConnection()))
{
    con.Open();
    SQLiteCommand cmd = new SQLiteCommand(con);
    count = cmd.ExecuteScalar(qry, tableName);
}

......但是我尝试编译的并不是什么类似的。

1 个答案:

答案 0 :(得分:7)

在此上下文中,ExecuteScalar返回System.Int64 应用(int)强制转换会创建您正在看到的异常

object result = cmd.ExecuteScalar();
Console.WriteLine(result.GetType());  // System.Int64

您可以使用Convert.ToInt32解决您的问题

SQLiteCommand cmd = new SQLiteCommand(qry, con);
count = Convert.ToInt32(cmd.ExecuteScalar());