且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

日期从java转换为oracle

更新时间:2023-11-29 13:50:58

从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,