3

I want to insert a date in the database, but it does not work any error message that appears. When I look at my table in Oracle DB I can not find my data that I inserted.

java.util.Date daterecep;
// getter and setter
public void setdaterecep( java.util.Date daterecep) {
         this.daterecep=daterecep;
} 
public  java.util.Date getdaterecep() {
       return  daterecep;
}

and

    nt val=0;
    try {
        val = st.executeUpdate("insert into tabdate (date) values('"+daterecep+"')" );
    } catch (SQLException ex) {
         Logger.getLogger(Insertdate.class.getName()).log(Level.SEVERE, null, ex);
    }

    System.out.println(val);
    return resultat;
}

I used PreparedStatement but it did not worked I just tried to execute the Java code

val = st.executeUpdate("insert into tabdate(date) values('12/12/2004')");

and add

public static void main (String args[]) throws SQLException {

    Insertdate B= new Insertdate();
    B.connexionBD();
    B.insert();//function for the insertion
}

and it works.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
hibara
  • 39
  • 2
  • 3
  • 5
  • possible duplicate of [Java Date - Insert into database](http://stackoverflow.com/questions/1081234/java-date-insert-into-database) – Basil Bourque Jul 03 '15 at 19:19

1 Answers1

15

Here,

values('"+daterecep+"')

you're basically attempting to store the result of daterecep.toString() in the database. As per the documentation this is in format like as "Sat Jun 6 10:43:00 BOT 2011" (which depends on the locale and timezone!). The database does not understand it.

You should be using PreparedStatement#setTimestamp() to set a DATETIME/TIMESTAMP field in a DB.

preparedStatement = connection.prepareStatement("insert into tabdate (date) values(?)" );
preparedStatement.setTimestamp(1, new Timestamp(daterecep.getTime()));
preparedStatement.executeUpdate();

Or when it's actually a DATE field, use setDate() instead.

preparedStatement.setDate(1, new java.sql.Date(daterecep.getTime()));

As a bonus, PreparedStatement also saves you from SQL injection attacks.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555