How to insert java.util.Date into the database?

I want to insert a date into the database, but no error message appears. When I look at my table in Oracle DB, I cannot 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 didn’t work. I just tried to execute 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.

+3
source share
1 answer

Here

values('"+daterecep+"')

you are basically trying to store the result daterecep.toString()in a database. According to the documentation, this is in a format such as "Sat Jun 6 10:43:00 BOT 2011" (which depends on the locale and time zone!). The database does not understand this.

You must use PreparedStatement#setTimestamp()to set the field DATETIME/ TIMESTAMPin the database.

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

, DATE, setDate().

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

PreparedStatement SQL-.

. :

+15

All Articles