簡體   English   中英

為什么使用此SQLite代碼會收到“無效的轉換異常”?

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

我有以下代碼可以從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;
}

當它運行時,我得到“ Invalid Cast Exception

顯而易見,從查詢返回的值是一個int,即記錄的計數(運行查詢時,我得到“ 2”,即Sqlite瀏覽器中的“ SELECT COUNT(*)FROM WorkTables”) 。

那么,這里被無效地投射了什么?

作為一個附帶說明,我知道使用查詢參數會更好,並且我在這里找到了如何在Windows Store應用程序中執行此操作[ 如何在WinRT應用程序中使用SQLite查詢參數? ,但不知道如何在舊版(Windows Forms / 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);
}

...但是我嘗試編譯的同類文件卻一無所有。

在這種情況下,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());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM