0

我有一种方法可以从表中的特定列中检索所有数据。现在这种方法在数据库中字段为“string”或“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
4

2 回答 2

2

尝试

timeList.Add(aReader.GetDateTime(0).ToString());
于 2012-05-03T11:44:06.723 回答
0

采用

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

你的日期格式可以在哪里"dd/mm/yyyy hh:MM:ss"或任何你想要的

于 2012-05-03T11:44:31.810 回答