简体   繁体   English

为什么使用此SQLite代码会收到“无效的转换异常”?

[英]Why am I getting “Invalid Cast Exception” with this SQLite code?

I've got this code to get a count from a SQLite table: 我有以下代码可以从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;
}

When it runs, I get, " Invalid Cast Exception " 当它运行时,我得到“ Invalid Cast Exception

As is probably obvious, the value being returned from the query is an int, that is to say the count of records (I get "2" when I run the query, namely "SELECT COUNT(*) FROM WorkTables" in Sqlite Browser). 显而易见,从查询返回的值是一个int,即记录的计数(运行查询时,我得到“ 2”,即Sqlite浏览器中的“ SELECT COUNT(*)FROM WorkTables”) 。

So what is being invalidly cast here? 那么,这里被无效地投射了什么?

As a sort of a side note, I know it's better to use query parameters, and I found out how to do this in a Windows Store App here [ How can I use SQLite query parameters in a WinRT app? 作为一个附带说明,我知道使用查询参数会更好,并且我在这里找到了如何在Windows Store应用程序中执行此操作[ 如何在WinRT应用程序中使用SQLite查询参数? , but don't know how to do it in an oldfangled (Windows Forms/Windows CE) app. ,但不知道如何在旧版(Windows Forms / Windows CE)应用程序中执行此操作。

I would think it would be something like this: 我认为应该是这样的:

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

...but nothing of the ilk that I tried compiled. ...但是我尝试编译的同类文件却一无所有。

In this context the ExecuteScalar returns a System.Int64 . 在这种情况下,ExecuteScalar返回System.Int64
Applying the (int) cast creates the exception you are seeing 应用(int)强制转换会创建您看到的异常

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

You could solve your problem with Convert.ToInt32 您可以使用Convert.ToInt32解决您的问题

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

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

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