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 开发者_StackOverflow社区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
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();
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());
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')";
精彩评论