日期从java转换为oracle [英] date conversion from java to oracle

查看:83
本文介绍了日期从java转换为oracle的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

如何将java中字符串类型的日期转换为oracle的日期类型。实际上我将日期从java插入到在oracle中创建的表中。它正在给出错误如下:



线程main中的异常java.sql.SQLException:ORA-01843:不是有效月份ORA-06512:第1行

Hello,
How to convert the date which is of string type in java to date type of oracle.Actually i am inserting date from java into a table created in oracle.It is giving error as follows.

Exception in thread "main" java.sql.SQLException: ORA-01843: not a valid month ORA-06512: at line 1

推荐答案

从java插入日期时,需要使用以下格式作为值。

You need to use below format as a value while inserting date from java.
To_date('01/11/2010', 'dd/mm/yyyy')



请参阅此 [ LINK ]了解更多信息。


Please refer to this [LINK] for more information.


Hello aghori,



理想情况下,您应该首先将字符串转换为java.util.Date,然后您应该使用预准备语句来插入日期。以下代码段可以帮助您理解这一点。它假定您已经知道捕获字符串日期的格式。对于下面的代码片段,我假设ISO日期格式。

Hello aghori,

Ideally you should first convert the string into java.util.Date and then you should use prepared statement to insert the date. The following snippet should help you understand this. It assumes that you already know the format in which the string date is captured. For the below code snippet I am assumes ISO date format.
Date dtToday = null;
DateFormat dtFmt = null;
PreparedStatement pstmt = null;

try {
    dtFmt = new SimpleDateFormat("yyyy-MM-dd");
    dtToday = dtFmt.parse(strDate);

    pstmt = con.prepareStatement("INSERT INTO tblfoo(first_name, last_name, dob) VALUES(?, ? ?)");
    pstmt.setString(1, strFirstName);
    pstmt.setString(2, strLastName);
    pstmt.setDate(3, dtToday);
    pstmt.execute();
} catch (ParseException ex) {
   log.error("Entered date {} has invalid format, expected yyyy-MM-dd", new Object[] {strDate});
}



如果你想使用日期文字,请使用以下语法。


If you want to use the date literal then use following syntax.

DATE '1998-12-25'



有关这方面的更多信息,请参阅 Oracle文档 [ ^ ]。使用Date literal,可以重写上面的代码,如下所示。但是字符串日期必须是ISO日期格式。


More information on this can be found in Oracle Documentation[^]. With Date literal the above code can be rewritten as shown below. However the string date must be in ISO Date format.

Statement stmt = null;

stmt = con.createStatement();
stmt.execute("INSERT INTO tblfoo(first_name, last_name, dob) VALUES('"
              .concat(strFirstName).concat("', '")
              .concat(strLastName).concat("', DATE '")
              .concat(strDate).concat("')"));



注意 - 上述方法容易受到 SQL Injection 攻击,因此不是首选方法。



问候,


Note - The above mentioned method is susceptible to SQL Injection attack and hence is not a preferred way.

Regards,


这篇关于日期从java转换为oracle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆