将sql中的日期字段与c#label中的日期进行比较 [英] Comparing date field in sql with a date from c#label

查看:69
本文介绍了将sql中的日期字段与c#label中的日期进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在sql数据库中有一个数据类型为"date"的field(dt),在我的C#格式中,标签中有一个日期(例如07-11-2011).我想写一阵子条件来与日期进行比较在数据库中...类似........

i have a field(dt) in sql database with datatype "date" and in my c# form there is a date in a label( like 07-11-2011).i wanna write a while condition to compare with a date in database...something like........

string query = "select name from vacseat where dt='"+lblDate.Text+"'";


它不起作用,请帮助


its not working ,plz help
thanx in advance.

推荐答案

将日期强制转换为varchar或将字符串强制转换为日期.现在,您正在尝试比较两种不同的数据类型.

另外,使用参数化查询或存储过程来避免可能的SQL注入攻击也是一个好主意.
either cast the date to a varchar or cast the string to a date. Right now you are trying to compare two different data types.

Also, it would be a very good idea to use parameterized query or stored procedure to avoid possible SQL injection attacks


首先,要有一个显示日期的Label并不是一个好主意(除非它实际上绑定到DateTime对象).如果是这种情况,则应在参数化查询中真正使用DateTime对象! 参数化查询使您对数据库的调用干净安全(不进行SQL注入!):)
该代码应如下所示:
First of all having a Label that displays a date is not such a good idea (unless it is actually bound to a DateTime Object). If that is the case you should really use your DateTime Object in a PARAMETERIZED QUERY!!!
Parameterized queries keep your calls to the database clean and safe (no SQL injection!) :)
The code should look something like this:
DateTime dt = DateTime.Today;
String query = "select name from vacseat where dt = @dt";
DbCommand cmd = new DbCommand(query, connectionObject); // Probably an SqlCommand or something.
cmd.Parameters.AddWithValue("@dt", dt); // Replaces @dt in your query with an actual date!
// Etc...


这应该可以解决问题:)
有关命令对象的更多信息,请参见此MSDN页面 [


This should do the trick :)
For more info on Command Object see this MSDN page[^].
Good luck! :)


首先,SQL Server中的日期格式(希望这是您的数据库技术),. NET中的日期格式必须与那里的格式匹配.通常,您在SQL Server中获得的格式不是直接匹配的.除非您将其转换为辅助SQL函数.可以帮助这种情况的SQL Server功能之一是转换 [
First of all, the date format in SQL Server(hoping this is your database tech.) and the date format in .NET has to match in there format. Usually the format you get in SQL Server is not directly match. Unless you convert it helper SQL function. One of SQL Server function that helps for such kind of case is Convert [^]function.So you query will look like
string query = "select name from vacseat where CONVERT(VARCHAR(10),dt,105)= '"+lblDate.Text+"'"; // Will format native SQL date time value to dd-mm-yyyy format

对此,Naerling关于SQL注入的建议对于数据库安全性非常有帮助.

主页,这将对您有帮助.

In addition to this what Naerling has suggest about SQL Injection is quite helpful for database safety.

Home this will help you well.


这篇关于将sql中的日期字段与c#label中的日期进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆