0

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.
5
  • 4
    Pretty much every database engine out there has something that returns the current date and time. Why not use that instead of dicking around with passing strings? Commented Feb 25, 2014 at 13:03
  • 1
    It's also better practice to use parameterized SQL queries Commented Feb 25, 2014 at 13:22
  • i am not using parameterized SQL queries, because i am building the query with if statments, i may have date = ... , date2 = ..., date4 = Commented Feb 25, 2014 at 13:48
  • @DanBracuk i did put "Now" as example, to show that it is System.dateTime format, but i do some calculations and then i want to put it on database, any suggestions? Commented Feb 25, 2014 at 13:59
  • @DanBracuk post your comment as an answer, i will accept it. thanks for the hint Commented Feb 25, 2014 at 14:07

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

Change

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

to

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

2 Comments

This approach will not work in case when DB using another culture
@MikkaRin how do i know what culture is my DB using?
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.