2015-01-06 128 views
0

我有一個在C#.NET和SQLite數據庫中實現的應用程序。我需要計算數據庫表(水果)的列(狀態)的一些值。表格如下。SQLite數據庫在C#.NET中查詢結果不正確

Id B M status 
1 10 101 2 
2 11 102 2 
3 11 103 0 
4 12 104 2 
5 13 105 2 
6 13 105 2 
7 14 106 2 
8 14 106 2 
9 14 106 2 
10 14 106 2 

我已經使用以下方法從表中提取值並顯示輸出。

public void CountingValues() 
     {  
     string strA, strB, strC; 
     double Total;    

     strA = countA(); 
     strB = countB(); 
     strC = countC();  

     MessageBox.Show(strA.ToString()); 
     MessageBox.Show(strB.ToString()); 
     MessageBox.Show(strC.ToString()); 

} 
    public string countA() 
    { 
     return GetData("SELECT COUNT(status) FROM fruit WHERE status = 2;"); 
    } 
    public string countB() 
    { 
     return GetData("SELECT COUNT(status) FROM fruit WHERE status = 1;"); 
    } 
    public string countC() 
    { 
     return GetData("SELECT COUNT(status) FROM fruit WHERE status = 0;"); 
    } 


    private String GetData(String cmd) 
    { 
     String result = ""; 
     SQLiteCommand command = new SQLiteCommand(connection); 
     command.CommandText = cmd; 
     SQLiteDataReader reader = command.ExecuteReader(); 
     while (reader.Read()) 
     { 
      result = reader[0].ToString();     
     } 
     reader.Dispose(); 
     command.Dispose(); 
     return result; 
    } 

strA,strB和strC的結果應分別爲9,0和1。但是,它顯示了4,0和6. 請問誰能告訴我這裏有什麼問題?

+1

我建議您使用替代查詢來顯示由.NET讀取的數據庫內容。我的猜測是你無意中附加了錯誤的數據庫。 –

+0

我的數據庫在應用程序運行時上傳。所以,沒有錯誤的數據庫連接的可能性。和,你在談論哪種替代查詢?你能解釋一下嗎? –

+0

我建議將'SELECT * FROM fruit'的結果用於診斷目的。 –

回答

1

嘗試使用選擇計數(*),而不是選擇計數(狀態)..此外,如果您正在使用visual studio在「result = reader [0] .ToString()」上放置一個斷點並查看正在存在的值填充。

任何時候我做數據庫調試我檢查,以確保數據表是相同的,我期望從sql查詢接收。在返回dt上放置一個斷點,並確保獲得與數據庫相同的數據結果,就像在數據庫上執行此查詢一樣。確保將sqlconnection對象更改爲您正在使用的類型。

public DataTable GetData() 
{ 
    SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString); 
    conn.Open(); 
    string query = "SELECT count(*) from fruit where status = 2"; 
    SqlCommand cmd = new SqlCommand(query, conn); 

    DataTable dt = new DataTable(); 
    dt.Load(cmd.ExecuteReader()); 
    return dt; 
} 
+0

它將需要將數據從DataTable轉換爲String或double,因爲它返回dt(DataTable)。是嗎? –

+0

它顯示錯誤 - 無法將類型爲「System.data.datatable」的對象轉換爲類型'system.IConvertible' –

+0

除了使用DataTable來計算值之外,還有其他的選擇嗎? –