Click here to Skip to main content
15,914,162 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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
Posted
Comments
Bernhard Hiller 2-Aug-13 5:55am    
Does Java lack the feature of "parameterized queries"? I can hardly imagine that.

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

Please refer to this [LINK] for more information.
 
Share this answer
 
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.
Java
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.
SQL
DATE '1998-12-25'

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

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

Regards,
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900