Friday, February 24, 2012

inserting the date into SQL Server problem

Im having problems inserting the current date into SQL server from my ASP.net application.

The error that asp.net throws is:

"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. "

In my page, im setting the date as follows:

Dim strDate as Date

strDate = now()

Then in my page I call a function called "do_store"

This works fin putting my variables into my database until I tried adding the date to the statement. Here is my function. Can anyone see my problem?

Public Function do_store(ByVal strTestID As String, ByVal strUserName As String, ByVal strUserID As String, ByVal strWrong As String, ByVal strRight As String, ByVal strAnswers As String, ByVal strDate As Date)
Dim strSQL As String
Dim sConn As String
Dim oConn As SqlConnection
'do the insert into the database
strSQL = "insert into test_results (test_plan_id, user_name, user_id, questions_wrong, questions_right, questions_answered, date_time) values (" & strTestID & ", '" & strUserName & "', " & strUserID & ", " & strWrong & ", " & strRight & ", " & strAnswers & ", '" & strDate & "')"
sConn = ConfigurationSettings.AppSettings("ConnectionString")
oConn = New SqlConnection(sConn)
Dim myCommand As SqlCommand

myCommand = New SqlCommand(strSQL, oConn)
myCommand.Connection.Open()
myCommand.ExecuteNonQuery()
End Function::Im having problems inserting the current date into SQL server from my ASP.net
::application.
::
::The error that asp.net throws is:
::
::"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. "

* Your datetime formates between the server and your process dont match.

Means: your server expects (for example) YMD, and you deliver YDM. Result: the date gets interpreted as month, and this can result in you "entering" month values from 13-31, which ARE out of range.

You need to make sure that the string you create actually is what the SQL Server expects.

BTW - if this is for a website, your code is insecure and very sucesseptable to a SQL INJECTION ATTACK.

Please read up the fundamental basics of SQL security - do it now.|||How do I check what format SQL Server wants?
how can I format the date so it fits into SQL server?
I got it all running locally (SQL Server and VS.NET) so Presumed their locale setting would be the same.
Im only building this as an intranet so its not open to the big bad world.|||This is explained in the SQL Server oducmentaiton. Actually you should not care - you should ALAWYS insert datetimes as ISO form, country independant. The correct way to insert this is:

return String.Format ("'{0:yyyy-MM-dd HH:mm:ss}'", Value);

At least this is what our EntityBroker O/R mapping framework uses, and it works so far.

The documentation of SQL Server has more information on this.

No comments:

Post a Comment