Java Date - Insert into database

 


your date is finally saved  as "2009-12-31"

So you can solve this problem in two ways:

1. Simply use setString(indexPosition, stringDatevalueInAboveFormat)
 
 2.Convert util.Date in sql.Date as below
 
    java.util.Date myDate = new java.util.Date("10/10/2009");

    PreparedStatement pstmt = connection.prepareStatement(
    "INSERT INTO USERS ( USER_ID, FIRST_NAME, LAST_NAME, SEX, DATE ) " +
    " values (?, ?, ?, ?, ? )");

    pstmt.setString( 1, userId );
    pstmt.setString( 3, myUser.getLastName() ); 
    pstmt.setString( 2, myUser.getFirtName() );  
    pstmt.setString( 4, myUser.getSex() );
    pstmt.setDate( 5, new java.sql.Date( myDate.getTime() ) );
 
As per the format question, using SimpleDateFormat will do:

String s = new SimpleDateFormat("dd/MM/yyyy").format( aDate );
 

 

No comments:

Post a Comment