Skip to Main Content
  • Questions
  • Inserting a Date Value Into Oracle using JDBC

Breadcrumb

Question and Answer

Tom Kyte

Thanks for the question, Vladimir.

Asked: August 03, 2000 - 10:46 pm UTC

Last updated: April 05, 2001 - 10:36 am UTC

Version: Oracle 8i

Viewed 1000+ times

You Asked

PROBLEM DESCRIPTION

I have an Oracle table and one of it's columns has a Date datatype. In my program I have a Date object. I want to place the value of the Date object into the Oracle table.

THE APPROACH I HAD IN MIND

I thought I'd use the "DateFormat.getDateTimeInstance(...)" to convert the Date object into a String object. I then thought I would use the oracle "TO_DATE" along with this String in the SQL UPDATE statement.

TWO ISSUES
FIRST - I don't know how to get "DateFormat.getDateTimeInstance(...)" to produce a time in 24 hour format. (i.e. 2:00 pm => 14:00). This is important as I must distinguish between 2am & 2 pm.

SECOND - Is there an easier way to do this? I get the feeling there must be a simpler way to store a Date into an Oracle DB using JDBC.

Any help would be appreciated.


and Tom said...

There are lots of ways to do it -- I myself prefer the TO_DATE/TO_CHAR method. I get all dates from the database in a STRING and I send them as a STRING. The date format I use on the way IN and OUT is:

'yyyy/mm/dd hh24:mi:ss'

The functions I generally use are:


static public java.util.Date strToDate(String s)
{
java.util.Date d = null;

if (s != null && s.length() == 19 )
{
d = new java.util.Date(
Integer.parseInt(s.substring(0,4)) - 1900,
Integer.parseInt(s.substring(5,7)) - 1,
Integer.parseInt(s.substring(8,10)),
Integer.parseInt(s.substring(11,13)),
Integer.parseInt(s.substring(14,16)),
Integer.parseInt(s.substring(17,19)));
}
return d;
}

static public String dateStr( java.util.Date x )
{
if ( x != null )
return (x.getYear()+1900) + "/" +
(x.getMonth()+1) + "/" +
x.getDate() + " " +
x.getHours() + ":" +
x.getMinutes() + ":" +
x.getSeconds();
else
return null;
}



You can also simply:

ResultSet rset = stmt.executeQuery("select DATECOL from TABLE");

while rset.next()
{
//get the date data
java.sql.Date date = rset.getDate(1);
....



Rating

  (1 rating)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Good ideas on handling datatypes

Harrison Picot, April 05, 2001 - 10:36 am UTC

If you are working with JSP (and I am) mapping datatypes seems like a huge pain and this helps figure it all out.