2013-01-21 57 views
0

我正在使用c#與SQL Server 2008.我正在創建一個項目,在其中我想要讀取來自數據庫的日期數。這些日期一個一個地存儲在一個列中。檢索到的數據應該添加到列表中。如何從數據庫中使用c#獲取單列數據(以及如何將其添加到列表中)

我的代碼是這樣的:

public List<DateTime> getholidays() 
{ 
    DataTable table = new DataTable("holidays"); 

    SqlCommand command = new SqlCommand(); 
    command.Connection = conn; 
    command.CommandType = System.Data.CommandType.Text; 
    command.CommandText = "select holiday from holidays"; 

    //conn.Open(); 
    SqlDataAdapter adapter = new SqlDataAdapter(command); 
    adapter.Fill(table); 

    List<DateTime> list=new List<DateTime>(); 

    foreach (DataRow row in table.Rows) 
    { 
     DateTime dt = new DateTime(); 
     dt = Convert.ToDateTime(row["holiday"]); 
     list.Add(dt); 
    } 

    conn.Close(); 
    return list; 
} 
+3

你有代碼,但如果你有特殊問題,你還沒有說明。有沒有按照你期望的方式工作? –

+0

問題是什麼?你的代碼看起來應該可以工作。 (當然,它可以通過使用'SqlDataReader'而不是DataTable來優化,但這不會影響正確性)。 – Dai

+0

看起來沒問題,「假期」列是什麼數據類型? – Lloyd

回答

0

我得到一個解決方案,我problem.thanks給大家。 這裏是我的新代碼

DataTable dt = new DataTable(); 
     List<DateTime> list = new List<DateTime>(); 

     SqlCommand cmd = new SqlCommand("select holiday from holidays1", conn); 
     SqlDataAdapter da; 
     da = new SqlDataAdapter(cmd); 
     dt.Clear(); 
     da.Fill(dt); 
     for (int i = 0; i < dt.Rows.Count - 1; i++) 
     { 
      list.Add(Convert.ToDateTime(dt.Rows[i][0])); 
     } 
     return list; 
2

關閉和傳播良好做法的緣故,你不需要清除數據表填寫之前,因爲它是一個新的對象。事實上,如果您使用DataReader,您甚至不需要DataTable。下面是我將如何實現您的代碼:

List<DateTime> dates = new List<DateTime>(); 

using(SqlCommand cmd = new SqlCommand("SELECT holiday FROM holidays1", conn)) 
using(SqlDataReader rdr = cmd.ExecuteReader()) { 

    while(rdr.Read()) { 

     dates.Add(rdr.GetDateTime(0)); 
    } 
} 

return dates; 

更短,更簡單,更快。

相關問題