2017-06-13 24 views
0

我想看看是否存在記錄使用C#和sqllite ..如何與sqllite和C#返回一個計數值

我的代碼如下

public static bool RecordExists(string fileName) 
     { 
      SetConnection(); 
      bool returnValue = false; 

      try 
      { 
       using (SQLiteCommand sqlCommand = new SQLiteCommand("select count(FileName) from downloadedfiles where fileName = '@Filename'", sql_con)) 
       { 
        sql_con.Open(); 
        sqlCommand.Parameters.Add(new SQLiteParameter("@FileName", fileName)); 
        long userCount = (long)sqlCommand.ExecuteScalar(); 
        if (userCount > 0) 
        { 
         returnValue = true; 
        } 

       } 
      } 
      catch (Exception ex) 
      { 
       throw new Exception(ex.Message); 
      }  


      return returnValue; 
     } 

兩件事情,

第一點 - 本來我有我的userCount爲int,但它一直說鑄錯誤...爲什麼它會這樣做?

二點 - 總是USERCOUNT返回0,即使存在與表相同的文件名數據..

感謝

+0

您是否嘗試過'Int32 userCount =(Int32)sqlCommand.ExecuteScalar();'?因爲select count返回一個整數類型。 – Joseph

+0

同樣的問題..說大小寫錯誤...我已經安裝了64位sqllite ..會導致一個問題? – user2206329

+0

也許你的查詢返回'null',不能轉換爲long。嘗試'Convert.ToLong(sqlCommand.ExecuteScalar());' – Joseph

回答

0
select count(FileName) 
from downloadedfiles 
where fileName = '@Filename' 
'@Filename'=>@Filename 
+0

OP面臨着不同的問題 – Eldho

+0

謝謝xsami - 這固定了我一直不歸零的問題 – user2206329

0

首先你不應該在參數使用引號。第二,你在查詢中命名參數@Filename,當你添加它時使用@FileName。這2個結果是你的查詢總是返回null。嘗試:

using (SQLiteCommand sqlCommand = new SQLiteCommand("select count(FileName) from downloadedfiles where fileName = @Filename", sql_con)) 
{ 
    sql_con.Open(); 
    sqlCommand.Parameters.Add(new SQLiteParameter("@Filename", fileName)); 
    int userCount = (int)sqlCommand.ExecuteScalar(); 
    if (userCount > 0) 
    { 
    returnValue = true; 
    } 
} 
相關問題