Ekas Preet Singh Ekas Preet Singh - 1 year ago 75
Java Question

How to Convert String type date to date for entry into oracle DB - Java

Incoming date format id 2014-11-03 and need to be converted to either 03/11/2014 or 03-Nov-2014.

What could be the best possible and smallest code?

Answer Source

OK so you have a String with the value 2014-11-03 and you want to insert that value in a DATE field inside a Oracle Database Table, usind Java's JDBC?

Well, first, convert that String into a Date object using a SimpleDateFormat object:

String s = "2014-11-03";
Date d = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss.S").parse(s);

Then, if you are using plain statements, reformat it the way Oracle would accept it in an SQL INSERT command, using again a SimpleDateFormat object:

String sd = new SimpleDateFormat("dd/MM/yyyy").format(d);

and insert it into your Satatement:

cn.createStatement().executeUpdate("INSERTRT INTO TABLE(...) VALUES(" + sd + ");

I would recommend you to better use a PreparedStatement instead of a plain SQL INSERT statement so your statement is sanitized:

PreparedStatement ps = cn.prepareStatement("INSERT INTO table VALUES(?, ?, ?)");

And then, insert your date as a Date object without the need of formatting into a String:

ps.setDate([index of the field to insert], d);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download