I Have a DataBase in my project With Table named 'ProcessData' and columns named 'Start_At' (Type: DateTime) and 'End_At' (Type: DateTime) .
When I try to enter a new record into this table, it enter the data in the following format: 'YYYY/MM/DD HH:mm', when I actualy want it to be in that format: 'YYYY/MM/DD HH:mm:ss' (the secondes dosen't apper). Does anyone know why, and what should I do in order to fix this?Here is the code I using:
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
SqlCom开发者_运维知识库mand command = new SqlCommand("insert into ProcessData (Start_At, End_At) values('" + startAt + "','" + endAt + "')", con);
command.ExecuteNonQuery();//execute the 'insert' query.
con.Close();
Many thanks
Use parametrized queries instead of building up the query using string concat like you're doing now.
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();
Also, use real dates (DateTime datatype) instead of strings that look like to be a date.
I've just tried this in SQL Server 2005, and I get that the record itself DOES contain the number of seconds.
Can you try:
select
Start_At,
convert(varchar(20), Start_At, 120) as Formatted_Start_At
from
ProcessData
and see if Formatted_Start_At contains the seconds value.
If so, your DB contains the actual values you expect of it, and so it's just a question of formatting your output.
精彩评论