Search code examples
javaoracledatetime

Inserting current date and time to Oracle database using Java


I want to insert current date and time in the format "yyyy-mm-dd hh:mm:ss" using Java. Which datatype is suitable for this, and which method of PreparedStatement do I need to use?


Solution

  • I assume the datatype of the column is DATE in the database. If you want to insert the current date and time, you can either use oracle's built in SYSDATE:

    ps = conn.prepareStatement('insert into your_table(date_col, ...) values (sysdate, ...)');
    

    Or parameterize it and use setTimestamp() on PreparedStatement:

    ps = conn.prepareStatement('insert into your_table (date_col, ...) values (?, ...)');
    ps.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis()));
    

    As suggested by @Basil in the comments below, You can also use java.time.Instant class:

    ps.setObject(1 , Instant.now());
    

    and while retrieving , use ResultSet#getObject(int/String, Class<T>):

    Instant i = rs.getObject(1, Instant.class);