简体   繁体   中英

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.

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

Change

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

to

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

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM