How to query Data values on a C# connection to excel using Oledb?

Asked

Viewed 56 times

0

Follow below the line of code

private void button7_Click(object sender, EventArgs e)
        {
            string conex = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + textBox1.Text + ";Extended Properties=\"Excel 8.0;HDR=YES;\";";
            OleDbConnection conn = new OleDbConnection(conex);

            OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("SELECT * FROM  [" + textBox2.Text + "$] where DATA ="+ dateTimePicker1.Value , conn);
            DataTable dt = new DataTable();

            myDataAdapter.Fill(dt);
            dataGridView1.DataSource = dt;
}

I try to return a value by searching for Data, but only find errors. No single quotes(as in the code), returns error =

System.Data.OleDb.OleDbException: 'Erro de sintaxe (operador faltando)
na expressão de consulta 'DATA =18/12/2020 08:20:04'.'

When I put single quotes in the query around the error dateTimePicker =

System.Data.OleDb.OleDbException: 'Tipo de dados imcompatível na
expressão de critério.'
  • No, DATA is the column name of all the Dates, and I want to fetch the values.

1 answer

0


Your database may not understand the date format. Usually it works with the format YYYY-MM-DD.

Include the method ToString in his dateTimePicker1.Value explaining in which format the date should be written in the query.

OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("SELECT * FROM  [" + textBox2.Text + "$] where DATA ="+ dateTimePicker1.Value.ToString("yyyy-MM-dd HH:mm:ss") , conn);
  • My database I am using is an excel spreadsheet, the format is dd-MM-yyyy HH:mm:ss . now it runs, but returns no value

  • Then the error was solved. Now attention has to be given to the values of the bank and the criterion. When using the same operator, ensure that the value sought is identical to those in the bank. In the case of Datetime this includes up to the thousandths of a second.

  • I did, include a "like" in the query to search for the other values after the date. Thank you!!!

  • Cool! If this solution helped you circumvent the error, mark this response as you accept it to be completed. Hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.