|
-
Jan 15th, 2009, 09:17 PM
#1
Thread Starter
Addicted Member
about datetime for insert to database
when i want to insert datetime to database
sometime is good but sometime is error
this is code
datetimesales = format(now,"dd/MM/yyyy hh:mm")
what's happen?
-
Jan 15th, 2009, 09:24 PM
#2
Re: about datetime for insert to database
There should never be an issue inserting dates into databases because they should be inserted the same way every other value is inserted and every other value should be inserted using parameters. When you start converting values to strings and inserting them into another string you open yourself up to all sorts of issues, this among them. Just use parameters and all those problems go away, e.g.
vb.net Code:
Dim command As New SqlCommand("INSERT INTO MyTable ([Date]) Values (@Date)", connection) command.Parameters.AddWithValue("@Date", Date.Now)
That's what you should ALWAYS be doing to insert variables into SQL statements.
-
Jan 16th, 2009, 03:37 PM
#3
Re: about datetime for insert to database
I entirely agree with that, but thought you might like to know the reasons for the original failure.
The problem is that you made an assumption which is common, and entirely wrong - that the database uses the date format you have specified somewhere (in Control Panel, or within the database system, etc), and it does not. Internally dates do not have a format at all, and via SQL statements the database system has its own specific format that you need to adhere to (the format you used is not right for any database system I've ever seen). While you were providing the date in the format dd/MM/yyyy, it was being interpreted using an entirely different format.
If you use parameters as shown above, this is one of many problems that goes away (others include the ' character in text fields). For further info see the article Why should I use Parameters instead of putting values into my SQL string? from our Database Development FAQs/Tutorials (at the top of the Database Development forum).
Last edited by si_the_geek; Jan 16th, 2009 at 03:40 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|