2012-06-19 26 views
2

我有一個簡單的問題,即使有很多谷歌搜索,我仍然無法找到答案。也許發佈這個問題將有助於下一個尋找相同答案的可憐的靈魂。返回列表<int>來自數據庫

我有一個查詢,返回不同ID的集合。

我正在用此查詢創建一個SQLCommand並使用ExecuteScalar()來運行它。

ExecuteScalar()似乎返回一個對象,並不會允許我將它轉換爲List。

解決這個問題的最佳做法是什麼?如何解決這個問題?

回答

5

執行標返回一個數據塊。認爲一行,一列。如果你想返回一個集合,你需要撥打ExecuteReader()。這將返回一個IDataReader。然後您可以遍歷記錄並返回您的列表。

2

ExecuteScalar() - 只返回第一行和第一列....

檢查MSDN:SqlCommand.ExecuteScalar

您需要用戶像這樣得到結果即ExecuteReader

using (IDataReader reader = 
     command.ExecuteReader(CommandBehavior.CloseConnection)) 
{ 
     List<int> intlist = ReadList(reader); 
} 

方法創建列表

List<int> ReadList(IDataReader reader) 
{ 
    List<int> list = new List<int>(); 
    int column = reader.GetOrdinal("MyColumn"); 

    while (reader.Read()) 
    { 
     //check for the null value and than add 
     if(!SqlReader.IsDBNull(column)) 
      list.Add(reader.GetInt32(column)); 
    } 

    return list; 
} 
+0

這一點,如果返回一個空分貝值都將拋出。 –

+0

@JasonMeckley - 謝謝指點,我只是改進了代碼............ –

+0

沒問題。我不止一次遇到過這個問題 –

3

ExecuteScalar

執行查詢,並在查詢返回的結果集返回第一行的第一列。 忽略其他列或行

您需要使用SqlDataReader

SqlCommand command = new SqlCommand(queryString, connection); 
IList<int> ints = new List<int>(); 
using(SqlDataReader reader = command.ExecuteReader()) { 
    while (reader.Read()) 
    { 
     ints.add(reader.GetInt32(0)); // provided that first (0-index) column is int which you are looking for 
    } 
} 
2

ExecuteScalar方法返回查詢返回的結果集中第一行的第一列。其他列或行將被忽略。

如果你想有一個項目列表,您應該使用ExecuteReader和環通閱讀器和閱讀的價值需要

List<int> items=new List<int>(); 
using (IDataReader reader = db.ExecuteReader(dbCommand)) 
{ 
     while (reader.Read()) 
     { 
     items.Add(reader.GetInt32(reader.GetOrdinal("YourColumnName")); 
     } 
} 
相關問題