为什么我使用此SQLite代码获得"无效的强制转换异常"?

B. *_*non 0 c# sqlite casting executescalar windows-ce

我有这个代码来从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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

作为一种旁注,我知道最好使用查询参数,我在这里找到了如何在Windows应用商店中执行此操作[ 如何在WinRT应用中使用SQLite查询参数?,但不知道如何在一个旧的(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);
}
Run Code Online (Sandbox Code Playgroud)

......但我尝试编译的类似之处.

Ste*_*eve 7

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

object result = cmd.ExecuteScalar();
Console.WriteLine(result.GetType());  // System.Int64
Run Code Online (Sandbox Code Playgroud)

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

SQLiteCommand cmd = new SQLiteCommand(qry, con);
count = Convert.ToInt32(cmd.ExecuteScalar());
Run Code Online (Sandbox Code Playgroud)