使用 DateTimePicker 从 Access 数据库检索记录时数据类型不匹配
当我尝试使用 C# 中的 DateTimePicker 从两个日期之间的访问数据库中检索记录时,出现数据类型不匹配条件表达式错误。
这是选择语句
else if (dtpDOBFrom.Value < dtpDOBTo.Value)
{
cmdSearch.CommandText = "SELECT [First Name], [Surname], [Contact Type], [Birthdate] FROM [Contacts] WHERE [Birthdate] >= '" + dtpDOBFrom.Value +"' AND [Birthdate] <= '" + dtpDOBTo.Value +"'";
}
I get a Data type mismatch criteria expression error when i try to retrieve records from an access database between two dates using a DateTimePicker in C#.
This is the Select statement
else if (dtpDOBFrom.Value < dtpDOBTo.Value)
{
cmdSearch.CommandText = "SELECT [First Name], [Surname], [Contact Type], [Birthdate] FROM [Contacts] WHERE [Birthdate] >= '" + dtpDOBFrom.Value +"' AND [Birthdate] <= '" + dtpDOBTo.Value +"'";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
dtpDOBFrom.Value
是一个 DateTime,您正尝试将其粘贴到字符串中。因此,DateTime 被转换为字符串,但格式似乎与 Access 期望的格式不同。您可以使用DateTime.ToString
的参数(并将日期括在#
而不是'
中,因为这是 Access 想要的),但这不是正确的做法。一般来说,避免此类类型转换问题(以及 SQL 注入等)的正确方法是使用 参数:
在您的情况下,它看起来像这样(未经测试):
使用 OLEDB(用于 MS Access 数据库访问),参数的名称(“DOBFrom”)并不重要,但添加它们的顺序必须与 SQL 中问号的顺序匹配。
dtpDOBFrom.Value
is a DateTime, which you are trying to paste into a string. Thus, the DateTime is converted into a string, but the format seems to be different from the format that Access expects. You could play with the parameters ofDateTime.ToString
(and enclose the date in#
instead of'
, since this is what Access wants), but that would not be the right way to do it.The right way, which avoids such type cast problems in general (and SQL injection, among other things), is to use parameters:
In your case, it would look something like this (untested):
With OLEDB (which is used for MS Access database access), the name of the parameters ("DOBFrom") is not important, but the order in which you add them must match the order of the question marks in the SQL.