为什么这个SQLite查询返回false?

时间:2015-01-19 20:00:37

标签: c# sqlite arguments

我有一个通用方法,用于查看给定表中给定列中是否存在至少一个具有给定值的记录。但是,当我这样称呼它时:

return ColumnInTableContainsStrValue("Inventory", "siteNum", NRBQConsts.currentSiteNum);

...它返回false,即使该表确实包含“siteNum”列为“03”的记录。这是有问题的方法:

public bool ColumnInTableContainsStrValue(String tableName, String 
columnName, String valToFind)
{
    ExceptionLoggingService.Instance.WriteLog("Reached
TestHHSDBUtils.ColumnInTableContainsStrValue");
    int count;
    string qry = String.Format("SELECT COUNT(*) FROM {0} WHERE {1} = 
@soughtValue", tableName, columnName)
    // TODO: temp - remove
    MessageBox.Show(String.Format("In ColumnInTableContainsStrValue; qry 
== {0}; valToFind == {1}", qry, valToFind));

    try
    {
        using (SQLiteConnection con = new 
SQLiteConnection(HHSUtils.GetDBConnection()))
        {
            con.Open();
            SQLiteCommand cmd = new SQLiteCommand(qry, con);
            cmd.Parameters.Add(new SQLiteParameter("soughtValue", 
valToFind));
            count = (int)cmd.ExecuteScalar();
        }
    }
    catch (Exception ex)
    {
        String msgInnerExAndStackTrace = String.Format(
            "{0}; Inner Ex: {1}; Stack Trace: {2}", ex.Message, 
ex.InnerException, ex.StackTrace);
        ExceptionLoggingService.Instance.WriteLog(String.Format("From 
TestHHSDBUtils.ColumnInTableContainsStrValue: {0}", 
msgInnerExAndStackTrace));
        return false;
    }
    return count > 0;
}

我在上面的方法中的临时MessageBox.Show()调用显示:

enter image description here

因此,一旦查询arg从@soughtValue转换为valToFind(“03”),查询应为:

SELECT COUNT(*) FROM Inventory WHERE siteNum = "03"

上面的查询在LINQPad中按预期工作:

enter image description here

那为什么它在“现实生活”中失败了?

注意: ColumnInTableContainsStrValue()中的catch块没有捕获任何内容 - 日志文件diebzg中没有任何内容。

更新

在更改catch块以捕获SQLiteException(代替通用Exception)之后,我得到了这个:

日期:2009年4月8日10:01:28 PM 消息:来自frmMain.ProcessNewDelivery:InvalidCastException;内部Ex :;堆栈跟踪:在HHS.TestHHSDBUtils.ColumnInTableContainsStrValue(String tableName,String columnName,String valToFind)    在HHS.frmMain.SiteInventoryHasBeenFetched()    在HHS.frmMain.ProcessNewDelivery()    在HHS.frmMain.menuItemFILE_NewDelivery_Click(对象发件人,EventArgs e)    在System.Windows.Forms.MenuItem.OnClick(EventArgs e)    在System.Windows.Forms.Menu.ProcessMnuProc(Control ctlThis,WM wm,Int32 wParam,Int32 lParam)    在System.Windows.Forms.Form.WnProc(WM wm,Int32 wParam,Int32 lParam)    在System.Windows.Forms.Control._InternalWnProc(WM wm,Int32 wParam,Int32 lParam)    在Microsoft.AGL.Forms.EVL.EnterMainLoop(IntPtr hwnMain)    在System.Windows.Forms.Application.Run(Form fm)    在HHS.Program.Main()

也许我必须用引号括住arg?

1 个答案:

答案 0 :(得分:2)

在SQLite中,ExecuteScalar的结果是Int64 所以从技术上讲,你的查询应该失败Invalid Cast Exception(在'现实生活中'和在LinqPad中)

您可以验证是否将您的通话更改为ExecuteScalar

 object result = cmd.ExecuteScalar();
 result.GetType().Dump();

因此,您只需将count的数据类型更改为long并将ExecuteScalar的返回值转换为long。
你在日志文件中没有看到任何内容的原因仍然是一种迷惑。

相关问题