简体   繁体   中英

How can I cast specific part of string type query to date to avoid “ORA-01843: not a valid month” error?

So I am trying to backup failed queries when the database is down and execute them immediately after database is ready. So far I am saving all the failed queries in text file. When the database is up I execute those failed queries line by line from the file. Since those failed queries are stored in string format, when I execute them for Oracle database (one column's datatype is date) I get ORA-01843: not a valid month. eg

INSERT INTO my_table ("MODULE", "USERNAME", "COMPUTER", "DATE","NAME", "EMAIL" ) values ('mymodule', 'mmouse', 'mickey007', '06-03-2015 12:05:00', 'Mickey Mouse', 'mmickey@gmail.com')

Since there is going to be a lot of this kind queries in the fail_queries file what could be the ways to cast just '06-03-2015 12:05:00' part of string to date

Thanks beforehand!!!

Do not pass DateTime as string, instead use Parameters.

If you have to pass a string then you have to convert it to date using TO_DATE like in your case:

TO_DATE('06-03-2015 12:05:00', 'dd-mm-yyyy hh24:mi:ss')

But, if you are sending values through C#, then instead of concatenating values, use Parameters. like:

using(OracleConnection connection = new OracleConnection("yourConnectionString"))
using (
    OracleCommand command =
        new OracleCommand(@"INSERT INTO my_table (MODULE, USERNAME, COMPUTER, DATE,NAME, EMAIL ) 
           values (:myModule, :mmouse,:mickey007, :myDateTime,:myothercol, :myEmail", connection))
{
    //add parameters
    command.Parameters.Add(":myModule", OracleDbType.Varchar2).Value = "myModule";
    command.Parameters.Add(":myDateTime", OracleDbType.Date).Value = DateTime.Now; // like this
    //add other parameters similarly. 
    connection.Open();
    //execute command

}

Parameters will not only save you from errors like these, but also save you from SQL Injection .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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