简体   繁体   English

查询字符串数据类型不匹配

[英]query string data type mismatch

I'm using OLEDB to query an excel file using date time picker but I keep getting a Data type mismatch in cireria expression error. 我正在使用OLEDB使用日期时间选择器查询Excel文件,但是在Cireria表达式错误中,我一直遇到数据类型不匹配的情况。

The format in excel for the date is "6/08/2012 10:00" 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();

You are passing time to the query as a string, so you could ToString() it to make it work: 您将时间作为字符串传递给查询,因此您可以使用 ToString()使其起作用:

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

But you really should make it a parameter. 但是您确实应该将其设为参数。 Plus, it's safer that way. 另外,这样更安全。

    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
        }
    }

Find out more: OleDbParameter Class 了解更多信息: OleDbParameter类

Create an OleDbCommand and pass the value in as a parameter. 创建一个OleDbCommand并将值作为参数传递。 Then use the Command as a parameter for the OleDbAdapter constructor... 然后使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM