SQL查询的日期时间 [英] date time a sql query
本文介绍了SQL查询的日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好,
我有c#应用,我正在比较日期之间的查询,但无法识别比较.错误是
在需要条件的上下文中指定的非布尔类型的表达式,接近"10/31/2012 09:00:00م".
这是我的代码
Hello,
I''ve c# app, I''m comparing in query between dates ,it doesn''t recognize the comparison .The error is
An expression of non-boolean type specified in a context where a condition is expected, near ''10/31/2012 09:00:00 م''.
Here''s my code
string x=textBox1.Text;
string y=textBox1.Text;
DateTime fro=Convert.ToDateTime (x);
DateTime to=Convert.ToDateTime (y);
SqlConnection con = new SqlConnection(@"Data Source=.\Ahmed;Initial Catalog=Market;Integrated Security=True");
cmd=new SqlCommand ( "SELECT dat , product_id FROM market where dat >= '" + fro + "' and '"+to+"' ",con);
con.Open();
dr = cmd.ExecuteReader();
DataSet sd = new DataSet(); ;
while (dr.Read())
{
DateTime d = (DateTime)dr["dat"];
if (d >= fro && d <= to)
{
}
}
dr.Close();
如何将datareader的结果发送到数据集?
How to send the result of datareader to dataset?
推荐答案
首先,我遇到了一个类似的问题,即转换为datetime是正确的,但是月份变成了日期.
查看 http://msdn.microsoft.com/en-us/library/9xk1h71t.aspx [ ^ ]来查看区域性格式.
第二个SELECT dat,product_id FROM市场,其中 dat> = YOUR_FIRST_DATE和??? ()您必须指定要比较的内容.
建议:在调试会话中查找将要运行的命令,然后在sql server(或您使用的服务器)中运行该命令
Well first i had a problem similar in which, the conversion to datetime was correct, but the month became the day.
Look at http://msdn.microsoft.com/en-us/library/9xk1h71t.aspx[^] to see the culture format.
Second SELECT dat , product_id FROM market where dat >= YOUR_FIRST_DATE and ??? () you mush specify what do you want to compare.
Advise: look in the debug session and get the command that will be run, and run it in sql server(or what you use)
使用SQL BETWEEN Operator .看看下面的链接.
http://www.w3schools.com/sql/sql_between.asp
编辑
不要将输入控件(文本框)的值连接到查询中.考虑到 SQL注入,这是潜在的高风险.
http://en.wikipedia.org/wiki/SQL_injection
http://msdn.microsoft.com/en-us/library/ms161953 (v = sql.105).aspx
要解决问题,请尝试以下代码.
Use SQL BETWEEN Operator. Have a look at below link.
http://www.w3schools.com/sql/sql_between.asp
Edit
Do not concatenate values of input controls(textbox) to your query. This is potential high risk considering SQL Injection.
http://en.wikipedia.org/wiki/SQL_injection
http://msdn.microsoft.com/en-us/library/ms161953(v=sql.105).aspx
Comming to solution, try as below code.
cmd=new SqlCommand ( "SELECT dat , product_id FROM market where dat BETWEEN @fro and @to ",con);
cmd.Parameters.Add("@fro", SqlDbType.VarChar);
cmd.Parameters("@fro").Value = x;
cmd.Parameters.Add("@to", SqlDbType.VarChar);
cmd.Parameters("@to").Value = y;
这篇关于SQL查询的日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文