Insert timestamp value in PreparedStatement

Problem

A simple table script in Oracle database.


CREATE TABLE DBUSER ( 
  USER_ID       NUMBER (5)    NOT NULL, 
  USERNAME      VARCHAR2 (20)  NOT NULL, 
  CREATED_BY    VARCHAR2 (20)  NOT NULL, 
  CREATED_DATE  DATE          NOT NULL, 
  PRIMARY KEY ( USER_ID ) 
 )

No idea how to insert a timestamp value, e.g. “04/04/2011 14:45:04” into “CREATED_DATE” field, via JDBC PreparedStatement.


String insertTableSQL = "INSERT INTO DBUSER"
		+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
		+ "(?,?,?,?)";
preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setTimestamp(4,???);

Solution

Create a method to return current timestamp(java.sql.Timestamp) like this :


private static java.sql.Timestamp getCurrentTimeStamp() {

	java.util.Date today = new java.util.Date();
	return new java.sql.Timestamp(today.getTime());

}

And set the timestamp via preparedStatement.setTimestamp().


String insertTableSQL = "INSERT INTO DBUSER"
	+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
	+ "(?,?,?,?)";
preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setTimestamp(4,getCurrentTimeStamp());

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
4 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
4 Comment authors
Ryandobluthchiewilliam Recent comment authors
newest oldest most voted
william
Guest
william

I am extremely impressed with your writing skills as well as with the layout on your weblog.
Is this a paid theme or did you customize it yourself?
Anyway keep up the excellent quality writing, it’s rare to see a great blog like this one these days.

chie
Guest
chie

This was a great quick help: its conciseness is much appreciated.

dobluth
Guest
dobluth

I wonder, why you are not just using the following statement:

new java.sql.Timestamp(System.currentTimeMillis())

There is no need to construct a Date object beforehand.

Ryan
Guest
Ryan

Sure this is great for getting the current time, but what about getting any other time. Say we wanted to get input from a user or set a time that was in the past.