views:

115

answers:

2

Hi,
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
SqlCommand command = new SqlCommand("insert into ProcessData (Start_At, End_At) values('" +  startAt + "','" + endAt + "')", con);
command.ExecuteNonQuery();//execute the 'insert' query.
con.Close();

Many thanks

A: 

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.

Frederik Gheysels
Thanks for your fast answer, I tried what you have suggest, however, it still doesn't work.Regarding to what you said about using DateTime insted of String: I tried this at the first time, but then I got the following exception:"System.Data.SqlClient.SqlException: The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. The statement has been terminated."best regards,
menacheb
A: 

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.

Neil Moss