[英]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.我正在尝试从我的访问数据库中获取在 2 个日期之间订购的订单列表。 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. 2 个文本框直接从 2 个 ajax 日历扩展器接收日期。 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".
我已经确保第一个日期在第二个日期之前,并且我已经确保插入数据库的数据也像“#”+date+“#”一样插入,但我“查询表达式中的数据类型仍然不匹配” . 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 ?
Access 数据库查询使用
?
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.