0

我正在使用 OLEDB 使用日期时间选择器查询 excel 文件,但我不断收到 cireria 表达式错误中的数据类型不匹配错误。

excel中日期的格式是“6/08/2012 10:00”

        DateTime time = dateTimePicker1.Value;            

        MyCommand = new OleDbDataAdapter("select * from [CR$] where ([Req Start Date] >='" + time + "')", MyConnection);



        DtSet = new System.Data.DataSet();
        MyCommand.Fill(DtSet);


        bindingSource1 = new BindingSource();
        bindingSource1.DataSource = DtSet;
        bindingSource1.DataMember = DtSet.Tables[0].TableName;
        dataGridView1.DataSource = bindingSource1;

        MyConnection.Close();
4

2 回答 2

1

您将时间作为字符串传递给查询,因此您可以ToString() 使其工作:

MyCommand = new OleDbDataAdapter("select * from [CR$] where ([Req Start Date] >='" + time.ToString("%M/dd/yyyy HH:mm") + "')", MyConnection);

但是你真的应该把它作为一个参数。另外,这样更安全。

    using (OleDbConnection connection = new OleDbConnection(yourConnectionString))
    {
        OleDbDataAdapter adapter = new OleDbDataAdapter("select * from [CR$] where [Req Start Date] >= ?", connection);
        adapter.SelectCommand.Parameters.Add("@p1", OleDbType.Date);
        adapter.SelectCommand.Parameters["@p1"].Value = time;

        try
        {
            connection.Open();
            adapter.Fill(DtSet);
        }
        catch (Exception ex)
        {
            //handle error
        }
    }

了解更多:OleDbParameter 类

于 2012-11-21T22:12:56.440 回答
0

创建一个 OleDbCommand 并将值作为参数传入。然后使用 Command 作为 OleDbAdapter 构造函数的参数...

string queryString = "select * from [CR$] where ([Req Start Date] >= ?)";
OleDbCommand command = new OleDbCommand(queryString, connection);
command.Parameters.Add("@p1", OleDbType.DateTime).Value = time;
MyCommand = new OleDbDataAdapter(queryString, MyConnection);
于 2012-11-21T22:14:06.920 回答