dyk
dyk

Reputation: 121

Insert/Update SQL DateTime From asp.net(C#) System.dateTime

Here is what i am trying to do:

NOTE: I don't want to use parameterized queries.

Code:

 refresh_query.Append("UPDATE Table SET ");
 System.DateTime now = System.DateTime.Now;
      refresh_query.Append("date='" +now + "' ");
      refresh_query.Append("WHERE user_id='1'");

which results in this query:

 UPDATE Table SET date='25/02/2014 12:04:00'
 WHERE user_id='1'

getting the following error:

   An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll 
but was not handled in user code
Additional information: The conversion of a varchar data type to a datetime data 
type resulted in an out-of-range value.

Upvotes: 0

Views: 1549

Answers (3)

Dan Bracuk
Dan Bracuk

Reputation: 20804

Pretty much every database engine out there has something that returns the current date and time. Why not use that instead of passing strings?

Upvotes: 2

MikkaRin
MikkaRin

Reputation: 3084

Check how date stores in sql by using

select getdate()

In your code

refresh_query.Append("date='" +now.ToString(_formatExpression_) + "' ");

where formatExpression - is format that corresponds to format of date in your SQL (http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo(v=vs.110).aspx#properties)

Upvotes: 0

Ramesh Rajendran
Ramesh Rajendran

Reputation: 38693

Change

refresh_query.Append("date='" +now + "' "); 

to

refresh_query.Append("date='" +now.ToString() + "' ");

Upvotes: 0

Related Questions