Reputation: 7008
Before finishing off the coding, I would like to know what would be the best way to insert date and time stamp in database using java.
Database could be oracle, mssql, db2 or mysql.
I want to insert date and time stamp in a way so that its retrieval should be easy for reconciliation of records. Lets say our DB admin might want to pull records between range Aug 2015 and Oct 2015 and some time range as well.
Option 1: using different sql query scripts for each database type
Example:
INSERT INTO YOUR_TABLE (YOUR_DATE_COLUMN, COLUMN_2, COLUMN_3)
VALUES (SYSDATE, 1234, 567);
Option 2: using java syntax as follows
Example:
java.util.Date date = new java.util.Date();
long t = date.getTime();
java.sql.Date sqlDate = new java.sql.Date(t);
java.sql.Time sqlTime = new java.sql.Time(t);
java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(t);
pstmt.setDate(2, sqlDate);
pstmt.setTime(3, sqlTime);
pstmt.setTimestamp(4, sqlTimestamp);
pstmt.executeUpdate();
Would option 2 handle proper insertion of date and timestamp in different db types?
Upvotes: 2
Views: 3985
Reputation: 124648
Would option 2 handle proper insertion of date and timestamp in different db types?
Assuming that you used the right Java types matching the underlying column types, yes that's the idea.
Note that in the example you gave, you set columns 2, 3, 4, but not 1. You will obviously need to set column 1 too, and they should match with columns in the SQL string (you didn't include), with ? placeholders for the values for the appropriate columns.
In any case, check the documentation of the jdbc drivers of the databases you want to work with, look at the implementation notes concerning the mapping of Java types to SQL types, and any potential documented gotchas.
Upvotes: 2
Reputation: 12021
Definitely option 2 will handle the insertion properly. At least better than option 1 :-) Of course you should create columns with proper data types in the database.
The things that you should be careful for are:
Upvotes: 1