Results 1 to 4 of 4
  1. #1
    wmd
    wmd is offline Member
    Join Date
    Jun 2012
    Posts
    15
    Rep Power
    0

    Default Problem INSERTing java.sql.Date into MySQL table

    I need to insert a date into a MySQL table. I'm using a PreparedStatement object. I understand that the date needs to be formatted as 'MM-dd-yy'. However, my date comes from a form where the user enters the date in the format dd-MM-yy' (or 'dd-MM-yyyy'). So, my question is, what's the best way to convert a String "dd-MM-yy" into a java.sql.Date object (which has the form of 'MM-dd-yy')?

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,802
    Rep Power
    19

    Default Re: Problem INSERTing java.sql.Date into MySQL table

    No it doesn't need to be formatted.
    You just use the setDate() method in PreparedStatement and pass in the Date object.

    Date objects have no format.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    wmd
    wmd is offline Member
    Join Date
    Jun 2012
    Posts
    15
    Rep Power
    0

    Default Re: Problem INSERTing java.sql.Date into MySQL table

    OK, thanks for the prompt answer. I was over-complicating it. Is this OK? ->

    Java Code:
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    Date dob = new Date(sdf.parse(request.getParameter("dob")).getTime());
    
    preparedStatement.setDate(1, dob);
    Or is there a way of doing it without using a SimpleDateFormat object?

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,802
    Rep Power
    19

    Default Re: Problem INSERTing java.sql.Date into MySQL table

    If the column in the database is a Date column then you really ought to be passing it a date.
    It's either that or change your INSERT so it does a to_date(), or whatever the MySQL equivalent is, on a string, but something needs to do the conversion.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. in java (csv into mysql) making problem in date formate
    By raj.mscking@gmail.com in forum New To Java
    Replies: 1
    Last Post: 06-08-2012, 10:08 AM
  2. problem with inserting into table
    By pardhu in forum AWT / Swing
    Replies: 2
    Last Post: 11-19-2011, 04:46 AM
  3. Replies: 4
    Last Post: 08-01-2011, 10:29 AM
  4. Replies: 3
    Last Post: 12-02-2010, 02:14 PM
  5. Inserting current date into a DB table
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 02-15-2008, 08:38 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •