从数据库中选择数据且条件为日期时,我收到此消息,指出条件表达式中的数据类型不匹配

When selecting data from database and the condition is date, I receive this message that data type mismatches in criteria expression

当从数据库中选择数据并且条件是日期时,我收到一条消息,指出条件表达式中存在数据类型不匹配。

这是我的代码。

public DataTable loadhooodor()
{
    DataTable hooodorDt = new DataTable();
    OleDbDataAdapter hooodorDa;
    hooodorDt.Clear();
    DateTime today = new DateTime();
    today = DateTime.Today;
    hooodorDa = new OleDbDataAdapter("select * from HoodoorEnseraf where heDate='"+ today+ "'", connection);
    hooodorDa.Fill(hooodorDt);
    return hooodorDt;
}

private void dataGridRefresh()
{
    dataGridView1.DataSource = null;
    dataGridView1.Update();
    dataGridView1.Refresh();
    dataGridView1.DataSource = loadhooodor();
}

我收到了这条消息。

我的访问数据table是,

检查您系统的日期格式和您发送日期的日期格式。

这是不使用参数化查询的问题之一。试试这个

hooodorDa = new OleDbDataAdapter("select * from HoodoorEnseraf where heDate=@today", connection);
hooodorDa.SelectCommand.Parameters.Add("@today",
                System.Data.SqlDbType.DateTime);
hooodorDa.SelectCommand.Parameters["@today"].Value = today;
hooodorDa.Fill(hooodorDt);

当您在 Access 中引用日期时,您必须在其周围放置 #This link gives more details

您还需要确保日期格式正确。您可以为此使用 ToString

因此您的代码变为:

hooodorDa = new OleDbDataAdapter("select * from HoodoorEnseraf where heDate=#"+ today.ToString("yyyy/MM/dd")+ "#", connection);