import java.sql.*;
import oracle.jdbc.*;

/**
 * This class is a sample that illustrates how to insert and access Date from 
 * Database with time precision. If you insert java.sql.Date and access it , the 
 * time part will be truncated during insert and access, hence we will have to 
 * insert and access Date as an instance of java.sql.Timestamp. This will 
 * hold the time precision during insert and access. To get milli second
 * precision the database column should be Timestamp instead of Date.
 * 
 */
public class DateTimeSample  {

  public DateTimeSample( ) throws SQLException {
    // Register Oracle Driver with DriverMananger
    DriverManager.registerDriver( new OracleDriver( ) );
  }

  public static void main( String[] args ) throws SQLException {
    DateTimeSample sample = new DateTimeSample( );
    int empno = 1111;
    sample.insertDateTime( empno );
    sample.getDateTime( empno );
  }

  // Insert date with time precision
  public void insertDateTime( int empno ) throws SQLException {
  
    Connection conn = this.getConnection( );
    
    // java.util.Date(). getTime() will return the current datetime in milliseconds
    Timestamp hireDate = new Timestamp( new java.util.Date( ).getTime( ) );
    
    PreparedStatement pstmt = conn.prepareStatement( " INSERT INTO EMP(EmpNo, HireDate) VALUES(?,?) " );
    
    pstmt.setInt( 1, empno );
    pstmt.setTimestamp( 2, hireDate );
    
    pstmt.executeUpdate( );
    System.out.println(" Employee record inserted : " + empno + "   " + hireDate );
    
    pstmt.close( );
    conn.close( );
  }
  
  // Access date with time precision
  public void getDateTime( int empno ) throws SQLException {
    
    Connection conn = this.getConnection( );   
    
    PreparedStatement pstmt = conn.prepareStatement( "SELECT HireDate FROM Emp WHERE EmpNo = ? " );
    
    pstmt.setInt( 1, empno );
    
    ResultSet rset = pstmt.executeQuery( );
    
    while ( rset.next( ) )
      System.out.println( " Get Employee HireDate    : " + empno + "   " + rset.getTimestamp( 1 ) );
    
    rset.close( );
    pstmt.close( );
    conn.close( );
  }
  
  // Returns a connection to database
  public Connection getConnection( ) throws SQLException  {
  
    // Change the connection string based on your database 
    // jdbc:oracle:thin:@dbhostname:port:dbSID
    String jdbcurl = "jdbc:oracle:thin:@localhost:1521:ias904";
    
    return DriverManager.getConnection( jdbcurl, "scott", "tiger" );    
  }
  
}