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

时间:2012-11-21 22:09:06

标签: c# sql visual-studio excel oledb

我正在使用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();

2 个答案:

答案 0 :(得分: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 Class

答案 1 :(得分: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);