In Java Operations on Oracle, date fields are a headache, but it is not difficult to grasp the matter carefully.
Give an example to illustrate:
There are name VARCHAR2 (20)//book names in table books, Buydate date//Purchase two fields.
A database connection has been created connection conn;
Method one, using Java.sql.Date to implement relatively simple YYYY-MM-DD format date.
Java.sql.Date does not support time format. Remember not to use the new java.sql.Date (int year,int month,int Date), because you also need to handle the time difference problem.
PreparedStatement pstmt = conn.preparestatement ("INSERT into book (name,buydate) VALUES (?,?)");
Java.sql.Date buydate=java.sql.date.valueof ("2005-06-08");
Pstmt.setstring (1, "Java Programming idea");
Pstmt.setdate (2,buydate);
Pstmt.execute ();
Method Two, use Java.sql.Timestamp, ditto do not use new Timestamp (...)
PreparedStatement pstmt = conn.preparestatement ("INSERT into book (name,buydate) VALUES (?,?)");
Java.sql.Timestamp buydate=java.sql.timestamp.valueof ("2004-06-08 05:33:99");
Pstmt.setstring (1, "Java Programming idea");
Pstmt.settimestamp (2,buydate);
Pstmt.execute ();
Method III, using Oracle's TO_DATE built-in functions
PreparedStatement pstmt = conn.preparestatement ("INSERT into book (name,buydate) VALUES (?, To_date (?, ' Yyyy-mm-dd hh24: Mi:ss ') ");
String buydate= "2004-06-08 05:33:99";
Pstmt.setstring (1, "Java Programming idea");
Pstmt.setstring (2,buydate);
Pstmt.execute ();