0

我的项目中有一个数据库,其中包含名为 'ProcessData' 的表和名为 'Start_At' (Type: DateTime) 和 'End_At' (Type: DateTime) 的列。
当我尝试在此表中输入新记录时,它以以下格式输入数据:'YYYY/MM/DD HH:mm',而我实际上希望它采用该格式:'YYYY/MM/DD HH :mm:ss' (没有出现秒数)。
有谁知道为什么,我应该怎么做才能解决这个问题?

这是我使用的代码:

con = new SqlConnection("....");
String startAt = "20100413 11:05:28";
String endAt = "20100414 11:05:28";
...
con.Open();//open the connection, in order to get access to the database
SqlCommand command = new SqlCommand("insert into ProcessData (Start_At, End_At) values('" +  startAt + "','" + endAt + "')", con);
command.ExecuteNonQuery();//execute the 'insert' query.
con.Close();

非常感谢

4

2 回答 2

1

使用参数化查询,而不是像现在这样使用字符串 concat 构建查询。

SqlCommand command = new SqlCommand();
command.Connection = someConnectionObj;
command.CommandText = "INSERT INTO Sometable (datecolumn) VALUES (@p_date)";
command.Parameters.Add ("@p_date", SqlDbType.DateTime).Value = someDate;
command.ExecuteNonQuery();

此外,使用真实日期(DateTime 数据类型)而不是看起来像日期的字符串。

于 2010-04-14T10:10:45.963 回答
0

我刚刚在 SQL Server 2005 中尝试过,我发现记录本身确实包含秒数。

你能试一下吗:

select 
    Start_At,
    convert(varchar(20), Start_At, 120) as Formatted_Start_At
from 
    ProcessData

并查看 Formatted_Start_At 是否包含秒值。

如果是这样,您的数据库包含您期望的实际值,因此这只是格式化输出的问题。

于 2010-04-14T16:32:26.760 回答