簡體   English   中英

查詢字符串數據類型不匹配

[英]query string data type mismatch

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

您將時間作為字符串傳遞給查詢,因此您可以使用 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類

創建一個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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM