简体   繁体   English

Java-创建Oracle日期字段

[英]Java - creating an oracle date field

I have an Oracle Date type to which I need to insert the current date. 我有一个Oracle Date类型,需要在其中插入当前日期。

I am using Java to generate this date but everything I've tried so far yeilds the following error: 我正在使用Java生成此日期,但是到目前为止,我尝试过的所有操作都会产生以下错误:

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

Can anyone suggest java code to generate a proper date? 谁能建议Java代码生成正确的日期?

Update: 更新:

The dates in the DB look like 11-DEC-06 数据库中的日期看起来像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: 我建议不要构建一个字符串查询(我猜你正在这样做),而应该使用PreparedStatement,它通常更容易(尤其是像这样的事情)而且更安全:

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();

根据您的要求,使用java.sql.Date或java.sql.Timestamp。

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. 如果要使用日期的字符串版本进行查询,则可能需要添加Oracle to_date函数。 You could do it like this (notice the extra d in the SimpleDateFormat) 您可以这样做(注意SimpleDateFormat中的多余d)

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')";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM