从Microsoft Access数据库中检索日期/时间值

时间:2012-05-03 11:37:55

标签: c# .net windows

我有一个方法可以检索表中特定列的所有数据。现在这个方法在数据库中的字符串是“字符串”或“int”(通过更改为GetInt32)格式时起作用,虽然它不喜欢日期字段,但我的方法如下:

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));

错误:

  

指定的演员表无效。

列中日期/字段的示例是:

02/05/2012 15:52:45

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

使用

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

您的日期格式可以是"dd/mm/yyyy hh:MM:ss"或任何您想要的