Results 1 to 3 of 3

Thread: about datetime for insert to database

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Dec 2008
    Posts
    144

    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?

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    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:
    1. Dim command As New SqlCommand("INSERT INTO MyTable ([Date]) Values (@Date)", connection)
    2.  
    3. command.Parameters.AddWithValue("@Date", Date.Now)
    That's what you should ALWAYS be doing to insert variables into SQL statements.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    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
  •  



Click Here to Expand Forum to Full Width