插入,选择和更新日期时间 [英] Insert, select and update DateTime

查看:270
本文介绍了插入,选择和更新日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有时间的表指定的列的时间和数据类型为日期

I have a table with time the column named time and the datatype is Date.

在asp.net我想查询插入日期,而另一间2日期,以便选择。

In asp.net I want a query to insert the date, and another so select between 2 date.

我已经尝试这样的:

string data = DateTime.Now.ToShortDateString(); //date= 28/10/2014 -> dd/mm/yyyy
string comando = "INSERT INTO example (date) values '" +data+ "+"'";

和我使用的查询2日期

select * 
from example 
where date >= '25/10/2014' and date <= '28/10/2014'

我已经尝试过与数据类型 VARCHAR ,但它不工作。所以我想用数据类型日期

I already tried with datatype varchar but it doesn't work. So I'm trying with the datatype date.

但是,当我执行查询插入我得到一个错误

But when I'm executing the query INSERT I get a error

从字符串转换日期和/或时间时,转换失败。

Conversion failed when converting date and/or time from character string.

有人请帮助我?唯一的问题我已经是时间保存到表中。

Somebody please can help me? The only problem I have is to save the time into the table.

如果可能,我想日期的格式为: DD / MM / YYYY

If possible I want that format of the date: dd/mm/yyyy

更新:

我有问题,更新的行有个约会(日期)和VARCHAR(名称) 这是我的code:

I'm having problem with update a row that have a date(date) and a varchar(name) That is my code:

string comando = "UPDATE example set name=@name WHERE data = @date";
SqlCommand cmd = new SqlCommand(comando, connect);
cmd.Parameters.Add("@name", nome);
cmd.Parameters.Add("@date", SqlDbType.Date).Value = data;
cmd.ExecuteNonQuery();

该messange错误是:字符串或二进制数据将被截断。 该语句已终止。

The messange error is: "String or binary data would be truncated. The statement has been terminated."

推荐答案

您应该绝不会拼接你的SQL命令在一起,就像你做!这将打开它们备份到SQL注入攻击。

You should NEVER concatenate together your SQL commands like you do! This opens them up to SQL injection attacks.

相反! - 使用参数这也摆脱了大量的转换问题

Instead - use parameters! This also gets rid of a lot of conversion issues.

所以,你的情况,你应该使用:

So in your case, you should use:

string comando = "INSERT INTO example (date) VALUES (@DateParam)";

,然后你需要设置 @DateParam 的SqlCommand

cmd.Parameters.Add("@DateParam", SqlDbType.Date).Value = YourDataValueHere

和应采取的所有的问题护理!

and that should take care of all your issues!

如果您要选择 - 再次,使用参数

If you want to select - again, use parameters!

select * 
from example 
where date >= @fromDate and date <= @toDate

当你从C#运行此。

如果你直接使用T-SQL(在管理室),然后使用 ISO-8601 格式年月日这是任何日期格式的indepdent和/或语言设置 -

If you use T-SQL directly (in Mgmt Studio), then use the ISO-8601 format YYYYMMDD which is indepdent of any dateformat and/or language settings -

select * 
from example 
where date >= '20141025' and date <= '20141028'

这适用于任何版本的SQL Server和任何日期格式,语言和区域settinsg。

This works on any version of SQL Server and with any dateformat, language and regional settinsg.

这篇关于插入,选择和更新日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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