2012-05-03 48 views
0

我有一種方法可以從表中的特定列中檢索所有數據。現在,當字段是「字符串」或「INT」(通過改變GetInt32等)格式的數據庫中的這種方法可行,但它不喜歡日期字段,我的方法如下:從Microsoft Access數據庫中檢索日期/時間值

public static void getDates() 
{ 
    //create the database connection 
    OleDbConnection aConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\ev_mgr.mdb"); 

    //create the command object and store the sql query 
    OleDbCommand actorCommand = new OleDbCommand("select Issue_Time2 from Events", aConnection); 
    try 
    { 
     aConnection.Open(); 

     //create the datareader object to connect to table 
     OleDbDataReader aReader = actorCommand.ExecuteReader(); 

     //Iterate throuth the database 
     while (aReader.Read()) 
     { 
      timeList.Add(aReader.GetString(0)); // Error occurs here 

     } 

     //close the reader 
     aReader.Close(); 

     //close the connection Its important. 
     aConnection.Close(); 
    } 

    //Some usual exception handling 
    catch (OleDbException e) 
    { 
     Console.WriteLine("Error: {0}", e.Errors[0].Message); 
    } 


    foreach (string time in timeList) 
    { 
     Console.WriteLine(time); 
    } 
} 

的拋出異常在這條線:

timeList.Add(aReader.GetString(0)); 

錯誤:

Specified cast is not valid.

在列的日期/字段的一個示例是:

02/05/2012 15:52:45 

回答

2

嘗試

timeList.Add(aReader.GetDateTime(0).ToString()); 
+0

它想在那裏。 [微軟告訴] [1] [1]:http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdatareader_methods%28v=vs.71%29.aspx –

+0

謝謝,我忽略了一些東西,它效果很好,謝謝! –

0

使用

timeList.Add(DateTime.Parse(aReader.GetString(0)).ToString(yourdateformat)); 

其中yourdateformat可以"dd/mm/yyyy hh:MM:ss"或任何你想

+0

嗨,謝謝,沒有工作:(我仍然得到相同的錯誤 –

相關問題