Insert date in Jdbc program


In this post we will Insert date in Jdbc with example/program in java

--Before executing java program execute these database scripts  >

create table EMPLOYEE(NAME varchar2(22), CREATION_DATE DATE);


--If table already exists then execute the DROP command >
drop table EMPLOYEE;


For inserting date in Jdbc use -
new java.sql.Date(new java.util.Date().getTime())


Example/program to Insert date in Jdbc java >
package d5_executeUpdate_INSERT;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class InsertDateJdbcExample {
   public static void main(String... arg) {
          Connection con = null;
          PreparedStatement prepStmt = null;
          try {
                 // registering Oracle driver class
                 Class.forName("oracle.jdbc.driver.OracleDriver");
                 // getting connection
                 con = DriverManager.getConnection(
                              "jdbc:oracle:thin:@localhost:1521:orcl", "ankit",
                              "Oracle123");
                 System.out.println("Connection established successfully!");
                 prepStmt = con
                              .prepareStatement("INSERT into EMPLOYEE (NAME, CREATION_DATE) "
                                            + "values (?, ?) ");
                 prepStmt.setString(1, "ankit");
                 prepStmt.setDate(2,
                              new java.sql.Date(new java.util.Date().getTime()));
                 // execute insert query
                 int numberOfRowsInserted = prepStmt.executeUpdate();
                 System.out.println("numberOfRowsInserted=" + numberOfRowsInserted);
                 prepStmt.close(); // close PreparedStatement
                 con.close(); // close connection
          } catch (ClassNotFoundException e) {
                 e.printStackTrace();
          } catch (SQLException e) {
                 e.printStackTrace();
          }
   }
}
/*OUTPUT
Connection established successfully!
numberOfRowsInserted=1
*/

Using above program we could Insert date in Jdbc in java


Let’s execute Sql query to fetch inserted date from EMPLOYEE table in Oracle >
SELECT TO_CHAR(CREATION_DATE,'MM/DD/YYYY HH24:MI:SS')CREATION_DATE from employee;




How to convert DATE to TIMESTAMP in Oracle?
SELECT CAST(CREATION_DATE AS TIMESTAMP) CREATION_DATE  FROM employee;


Labels: Core Java JDBC
eEdit
Must read for you :