简体   繁体   中英

Access Data type mismatch of date in sql query

I am trying to get a list of orders from my access database that were ordered between 2 dates. this is my query:

"SELECT * FROM Orders WHERE OrderDate >= '#" + DateTime.Parse(txtDate.Text) + "#' AND OrderDate <= '#" + DateTime.Parse(txtEndDate.Text) + "#'";

the 2 textboxes recieve the dates directly from 2 ajax calendar extenders. i have already made sure that the first date is before the second, and i had made sure that the data inserted to the database was also inserted like '#"+date+"#', but i "still data type mismatch in query expression". can anyone try and identify a problem with my query?

Assuming you have data like this:

var txtDate = new { Text = "2020-08-01" };
var txtEndDate = new { Text = "2020-08-01" };

your query might look like this:

var fromDate = DateTime.ParseExact(txtDate.Text, "yyyy-MM-dd",
                                 CultureInfo.InvariantCulture).ToString("yyyMMdd");

var toDate = DateTime.ParseExact(txtEndDate.Text, "yyyy-MM-dd",
                             CultureInfo.InvariantCulture).ToString("yyyMMdd");

var query =
    $"SELECT * FROM Orders WHERE OrderDate>='{fromDate}' AND OrderDate<='{toDate}'";

or the last part can be:

var query =
    $"SELECT * FROM Orders WHERE OrderDate BETWEEN '{fromDate}' AND '{toDate}'";

It is the octothorpes that are delimiters for date expressions, not single quotes . And the formatted text expression for a date value should be forced. Thus:

"SELECT * FROM Orders WHERE OrderDate >= #" + DateTime.Parse(txtDate.Text).ToString("yyyy'/'MM'/'dd") + "# AND OrderDate <= #" + DateTime.Parse(txtEndDate.Text).ToString("yyyy'/'MM'/'dd") + "#";

That said, look up how to run queries with parameters. It takes a few more code lines but is much easier to debug and get right.

You should use a parameterized query for both security and for type safety

Access database queries use ? as a placeholder for the parameters you pass.

OleDbCommand command = new OleDbCommand();

// I assume you have an oledb connection object and it is in open state
command.Connection = myConnection;
command.CommandText = "SELECT * FROM Orders WHERE OrderDate >= ? AND OrderDate <= ?";

// Please note that the name of the parameters are redundant and not used
command.Parameters.AddWithValue("StartDate", DateTime.Parse(txtDate.Text));
command.Parameters.AddWithValue("EndDate", DateTime.Parse(txtEndDate.Text));

// You can also use your data adatper. This is just an example
command.ExecuteReader();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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