Java JDBC How to - Save Java date to a TIMESTAMP column with the time zone information








Question

We would like to know how to save Java date to a TIMESTAMP column with the time zone information.

Answer

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.Date;
// w  ww  .  ja  v  a  2s.c o  m
// create table MyTable(
// os_name varchar(256)
// ts timestamp,
// ts_with_tz timestamp with time zone,
// ts_with_local_tz timestamp with local time zone
// )
public class Main {
  public static final void main(String[] argv) throws Exception {
    Class.forName("oracle.jdbc.OracleDriver");
    Connection conn = DriverManager.getConnection("your_connection_string",
        "your_user_name", "your_password");
    Date nowDate = new Date();
    Timestamp nowTimestamp = new Timestamp(nowDate.getTime());
    PreparedStatement insertStmt = conn
        .prepareStatement("INSERT INTO MyTable"
            + " (os_name, ts, ts_with_tz, ts_with_local_tz)"
            + " VALUES (?, ?, ?, ?)");
    insertStmt.setString(1, System.getProperty("os.name"));
    insertStmt.setTimestamp(2, nowTimestamp);
    insertStmt.setTimestamp(3, nowTimestamp);
    insertStmt.setTimestamp(4, nowTimestamp);
    insertStmt.executeUpdate();
    insertStmt.close();
    System.out.println("os_name, ts, ts_with_tz, ts_with_local_tz");
    PreparedStatement selectStmt = conn
        .prepareStatement("SELECT os_name, ts, ts_with_tz, ts_with_local_tz"
            + " FROM MyTable");
    ResultSet result = null;
    result = selectStmt.executeQuery();
    while (result.next()) {
      System.out.println(String.format("%s,%s,%s,%s", result.getString(1),
          result.getTimestamp(2).toString(), result.getTimestamp(3).toString(),
          result.getTimestamp(4).toString()));
    }
    result.close();
    selectStmt.close();
    conn.close();
  }
}