views:

55

answers:

3

I have an Oracle Date type to which I need to insert the current date.

I am using Java to generate this date but everything I've tried so far yeilds the following error:

java.sql.SQLException: ORA-01843: not a valid month

Can anyone suggest java code to generate a proper date?

Update:

The dates in the DB look like 11-DEC-06

SO, I've tried the following:

Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("d-MMM-yy");
String date = sdf.format(cal.getTime());

And this doesn't work

A: 

Use java.sql.Date or java.sql.Timestamp, depending on your requirements.

java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
Shane
yea I just figured the problem out. You are right, I was using a PreparedStament but setting the wildcard using setString instead of setDate...and I ended up using java.sql.Date..thanks
llm
+2  A: 

I would suggest instead of building a string query (which I am guessing you are doing), you instead use a PreparedStatement, which is generally easier (especially with things like this) as well as safer:

String rowToUpdate = "foo";
PreparedStatement ps = myConnection.prepareStatement(
      "UPDATE my_table SET date_field=? WHERE id=?");
Calendar cal = Calendar.getInstance();
java.sql.Date sqlDate = new java.sql.Date(cal.getTime().getTime());
ps.setDate(1, sqlDate);
ps.setString(2, rowToUpdate);
int updated = ps.executeUpdate();
M. Jessup
Wow thats pretty much the exact code I ended up using..I figured it out a second before you posted...so I'll accept your answer. Thanks
llm
A: 

If you are going to make the query using a String version of the date then you may need to add the Oracle to_date function. You could do it like this (notice the extra d in the SimpleDateFormat)

Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy"); String date = sdf.format(cal.getTime());

Then in the query you would put

String query = "select * from table where date_column=to_date('" + date +"','dd-Mon-yy')";

Winter