简体   繁体   English

如何在C#中编写SQL查询以查找DateTime?

[英]How do I write an SQL query in c# to find DateTime?

So I am creating a search function within my windows form that will allow the user to search for records based on what they have entered into the textbox. 因此,我在Windows窗体中创建了一个搜索功能,该功能将允许用户根据他们在文本框中输入的内容来搜索记录。 I have working code for finding records based off of every filter but the DateTime one. 我有工作代码,用于根据除DateTime之外的每个过滤器查找记录。 for example: 例如:

if (customerID_rb.Checked == true)
                {
                    sqlQuery = "SELECT CustomerID, CustomerName, Telephone, DateAndTime, Status, Description from Calls WHERE CustomerID = " + item;
                    //'item' is the text in the textbox
                    UsingCommand(conn, table, sqlQuery);
                    return table;
                }
private static void UsingCommand(SqlConnection conn, DataTable table, string sqlQuery)
    {
        using (SqlCommand cmd = new SqlCommand(sqlQuery, conn))
        {
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                da.Fill(table);
        }

    }

This will show the records containing the user entered text in the CustomerID column. 这将在“客户ID”列中显示包含用户输入的文本的记录。

However I cannot quite figure out how to do the same but for DateTime. 但是,除了DateTime,我无法完全弄清楚该如何做。 I know that in SQL you type 'WHERE 'DateTime = ...' but no matter how I try to reword the query string I just cannot get it to work. 我知道在SQL中键入“ WHERE'DateTime = ...”,但是无论我如何尝试重新编写查询字符串,我都无法正常工作。

The error I am getting is : 'SqlException was unhandled: An expression of non-boolean type specified in a context where a condition is expected, near 'DateAndTime'. 我得到的错误是:'SqlException未处理:在'DateAndTime'附近的期望条件的上下文中指定的非布尔类型的表达式。

Code: 码:

sqlQuery = "SELECT CustomerID, CustomerName, Telephone, DateAndTime, Status, Description from Calls WHERE DateTime DateAndTime  = '" + item +"'";

I have tried with and without the DateTime and in multiple different orders, if anyone can help me with this it would be greatly appreciated! 我尝试过和不使用DateTime并以多个不同的顺序进行尝试,如果有人可以帮助我,将不胜感激!

Thanks 谢谢

Edit: 编辑:

Ok... I messed up a little. 好吧...我弄乱了。 I wrongly assumed you would need the DateTime. 我错误地认为您将需要DateTime。 However, I may have been thrown off into thinking that because I get thrown an exception if I input the date and time wrong. 但是,我可能会想到,因为如果输入错误的日期和时间会引发异常。 Thanks! 谢谢! :) :)

You should never concatenate parameters into a SQL string. 永远不要将参数连接到SQL字符串中。

  • It leaves you vulnerable to SQL injection attacks . 它使您容易受到SQL注入攻击的攻击

  • It creates performance problems, as each unique value will create a new SQL query, having a different hash for the query, which defeats the execution-plan caching mechanism of the query engine. 它会产生性能问题,因为每个唯一值都会创建一个新的SQL查询,该查询具有不同的哈希值,从而破坏了查询引擎的执行计划缓存机制。

  • For date values, the ordering of y/m/d, d/m/y, or m/d/y string formats can be different depending on the current culture settings, the OS globalization settings, and the database server's globalization settings. 对于日期值,y / m / d,d / m / y或m / d / y字符串格式的顺序可能会有所不同,具体取决于当前的区域性设置,OS全球化设置以及数据库服务器的全球化设置。 If they're not all in sync, then you could end up with random weirdness like mistaking January 3rd for March 1st. 如果它们不完全同步,那么您最终可能会产生随机的怪异现象,例如将1月3日误认为3月1日。

Instead, you should always parameterize your queries! 相反,您应该始终参数化查询! The query gets a placeholder for the value, and then you add the value using a separate parameter. 该查询获取该值的占位符,然后使用单独的参数添加该值。 I'm not going to give you an example here, as it takes very little time to search for this on your own and there have already been hundreds of posts on this here on SO 我不会在这里给您举个例子,因为花费很少的时间自己搜索它,并且这里已经有数百篇关于SO的帖子。

您无需指定数据类型DateTime ,只需使用列名写查询即可,例如

sqlQuery = "SELECT CustomerID, CustomerName, Telephone, DateAndTime, Status, Description from Calls WHERE columnname = '" + item +"'";

Generally speaking, best would be to add sql parameters, but in string format: 一般来说,最好是添加sql参数,但以字符串格式:

  " ...   WHERE DateAndTime = '" + item.ToString("yyyyMMdd") +"'"

The yyyyMMdd should be safe to use in all cultures. yyyyMMdd应该可以在所有文化中安全使用。 The above is assuming, you have to search a date, not including time. 以上假设,您必须搜索日期,不包括时间。 Mostly times are only searched on with greater or smaller than. 通常,仅搜索大于或小于的时间。 Additional, if the date field itself contains time, and you only want to search the date: 另外,如果日期字段本身包含时间,而您只想搜索日期:

   "....   WHERE cast(DateAndTime as date)  = '" + item.ToString("yyyyMMdd") +"'"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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