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

I am getting the following error when inserting data into my oracle database.
java.sql.SQLException: ORA-01843: not a valid month
In database date is as: dd-MMM-yy (06-MAR-12)
I am converting 06-03-2012 to dd-MMM-yy by the following method:
String s="06-03-2012";
String finalexampledt = new SimpleDateFormat("dd-MMM-yy").format(new SimpleDateFormat("dd-MM-yyyy").parse(s));
So i got 06-Mar-12 which is same as the above database date format still i am getting the error. I am inserting as:
in index.jsp
String todaydate="";
Calendar calendar1 = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
todaydate = dateFormat.format(calendar1.getTime());
<input type="text" name="datename" value="<%=todaydate%>"/>
in servlet(doPost)
String s=request.getParameter("datename");
PreparedStatement ps=con.prepareStatement("insert into tablename(rest_dt, othercolname) values (to_date(?, 'dd-mm-yyyy'), ?)");
ps.setString(1, s);
ps.setString(2, otherstringdata);
int rs=ps.executeUpdate();
Any idea please

so make
("insert into mytablename (rest_dt) values to_date(?, 'DD-MM-YYYY')");
Try this
TO_DATE(?, 'DD-MM-YYYY','NLS_DATE_LANGUAGE = American')
// gets from Oracle docs

The datatype of your rest_dt columns is a DATE, so you need to supply one. You can use the TO_DATE function to convert a string to an Oracle DATE, so your insert statement
insert into tablename(rest_dt, othercolname) values (to_date(?, 'dd-mm-yyyy'), ?)
is fine.
Just make sure the string value you bind to your first ?-variable is in the format dd-mm-yyyy. And don't convert or format that value yourself: the TO_DATE function does that part.
There is no need to anything about session settings like nls_date_language here, since you have wisely chosen to use a language agnostic setting for the month with your MM mask (instead of MON).
Regards,
Rob.

Problem is that oracle uses NLS_DATE_LANGUAGE to get the current name of the month. So you should do
select * from nls_session_parameters
and check if you have the correct values. You can also check with the following select which name you get for the month
select TO_CHAR(TO_DATE('01-03-01', 'DD-MM-YY'), 'MON') from dual
I really don't understand why you insert the variable as a string value. Just use a date type (do the conversion on the client) in java and insert it without converting. If you really want to insert it as a string I would use a conversion to something like dd-MM-yyyy and insert it with TO_DATE(, 'DD-MM-YYYY').
Edit:
Do the conversion of the date on the client and use
ps.setDate(2, <yourDate>);

The same issue faced while running big query (multiple union) in Java and issue not with actual input since I have properly converted the with to_date('30-06-2021', 'dd-MM-yyyy') and found issue is with the date1 in query.
e.g.
select a,b,c from table1 where date1='31/12/2015'and date2=<actual input>
union
select a,b,c from table2 where date1='31/12/2015'and date2=<actual input>
union
select a,b,c from table3 where date1='31/12/2015'and date2=<actual input>
.
.
date1 also should be convert to to_date like below
e.g.
select a,b,c from table1 where date1=to_date('31/12/2015', 'dd-MM-yyyy') and date2=<actual input>
Hence issue resolved. My suggestions is, if you are getting such issues check the date part in the query and mention with to_date.
Java code:
#Autowired
private NamedParameterJdbcTemplate namedJdbcTemplate;
List<ResponseDTO> list = new ArrayList<>();
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("value1", dto.getValue1());
params.addValue("value2", dto.getValue2());
list = namedJdbcTemplate.query(SQL_QUERY, params, new CustomValueMapper());
Its purely only my own experience. Click up vote if it helps.

java.time and JDBC 4.2
Don’t transfer a date as a string to or from your database. Transfer a proper date object. I am assuming that your JDBC driver is at least JDBC 4.2 compliant. About all drivers are these days. In this case LocalDate is the type to use for dates, both in your Java program and in the transfer to the database.
So what you basically need is this:
LocalDate date = LocalDate.of(2012, Month.MARCH, 6);
PreparedStatement ps = con.prepareStatement(
"insert into tablename(rest_dt, othercolname) values (?, ?)");
ps.setObject(1, date);
ps.setString(2, otherstringdata);
int rs = ps.executeUpdate();
If you are receiving your date as string input from JSP, immediately parse it into a LocalDate object. There’s no need to wait until you need to put it into your database.
String inputString = "06-03-2012"; // Meaning 6 March 2012
LocalDate date = LocalDate.parse(inputString, DATE_PARSER);
I have been using this formatter:
private static final DateTimeFormatter DATE_PARSER
= DateTimeFormatter.ofPattern("dd-MM-uuuu", Locale.ROOT);
Links
Oracle tutorial: Date Time explaining how to use java.time.
Related question: Insert & fetch java.time.LocalDate objects to/from an SQL database such as H2

Related

Non-numeric character was found where a numeric was expected

I'm getting error as
ORA-01858: a non-numeric character was found where a numeric was expected
for a query in Eclipse but the same query is running fine in Toad.
I tried changing the date to to_char.
String query3 = "SELECT TXN_DATETIME FROM S3_ANTI_MONEY_LAUNDERING_TDS WHERE TRUNC(ROW_LOADED_DATE_TIME)='30-OCT-2018' AND SRC_FEED_NUM='63' AND BANK_ID IN('ISPP') AND SRC_RECORD_NUM IN('3','6')";
statement = connection.createStatement();
rs3 = statement.executeQuery(query3);
ArrayList<String> resultList1 = new ArrayList<String>();
while (rs3.next()) {
String result = rs3.getString(1) ;
resultList1.add(result);
The problem is likely the way that you have the date specified.
If you do not provide a proper date literal, then Oracle is using your NLS_DATE_FORMAT for the implicit conversion from text to date, and this might not be what you expect.
Replace this:
String query3 = "SELECT TXN_DATETIME FROM S3_ANTI_MONEY_LAUNDERING_TDS WHERE TRUNC(ROW_LOADED_DATE_TIME)='30-OCT-2018' AND SRC_FEED_NUM='63' AND BANK_ID IN('ISPP') AND SRC_RECORD_NUM IN('3','6')";
With this:
String query3 = "SELECT TXN_DATETIME FROM S3_ANTI_MONEY_LAUNDERING_TDS WHERE TRUNC(ROW_LOADED_DATE_TIME) = DATE '2018-10-30' AND SRC_FEED_NUM='63' AND BANK_ID IN('ISPP') AND SRC_RECORD_NUM IN('3','6')";
The proper way to do a DATE literal in Oracle is one of these:
DATE 'yyyy-mm-dd'
TIMESTAMP 'yyyy-mm-dd hh24:mi:ss'
Of course, you can use whatever mask you wish in this syntax:
TO_DATE('2018-10-30 00:00:00', 'YYYY-MM-DD HH24:MI:SS')
Oracle docs for NLS_DATE_FORMAT
Oracle docs for DATE and DATETIME literals
Finally, if your code is building that query on the fly, it's much better to use bind variables and a prepared statement. Just make sure you are familiar with the nuances of Java dates and timestamps vs. Oracle dates and timestamps.
Without seeing your database schema, I'd say this looks fishy:
SRC_RECORD_NUM IN('3','6')
I personally would NEVER declare a character field with a _NUM suffix, but your IN clause is passing character data. I bet you need to do:
SRC_RECORD_NUM IN (3,6)
But I'm guessing based entirely on the name of the field.

java.sql.SQLException: ORA-01843: not a valid month (Working in SQL DEVELOPER and doesn't work in JAVA)

I have a table in database that contains the 'Date_transaction' column his type is varchar.
In my Code JAVA, I create a SQL query via several conditions.
When I debug in Eclipse the query generated is like this:
SELECT *
FROM Transaction where 1=1
AND (to_date(Date_transaction,'YYYY/MM/DD HH:MI:SS') between '16/01/01' and '16/02/29')
AND projet = 'Project name'
AND nomtranche = 'tranche name' AND voletctrl = 'volet name'
AND (numeroimmeuble BETWEEN 1 AND 100)
AND validation = 1
AND statutDocNormal = 'statut'
AND numeroAppartement = 14
order by DateTrasaction DESC;
I execute this query in SQL DEVELOPER, the query is executed successfully without any error.
But in my code Java I get this Error : java.sql.SQLException: ORA-01843: not a valid month.
When I want to generate the query, I use this method to convert my date, this I spend in parameter (In the query it's : 16/01/01 and 16/02/29):
public static String parseDate2(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yy/MM/dd");
String dt = sdf.format(date);
return dt;
}
I try this answer but it's not working.
You are relying on the session's NLS_DATE_FORMAT, which is set differently in the client and probably indirectly via your Java locale. Use explicit conversion with a specific format mask:
... between to_date('16/01/01', 'RR/MM/DD') and to_date('16/02/29', 'RR/MM/DD') ...
But it would be better to use four-digit years and YYYY (remember Y2K?), or date literals - those those don't work with variable values.
This also looks wrong:
to_date(Date_transaction,'YYYY/MM/DD HH:MI:SS')
If `date_transaction is already a date then you are implicitly converting it to a string and then back to a date, which is pointless and dangerous. And then possibly back to a string to compare with your fixed values. If it is a string then it shouldn't be. Either way you need HH24 rather than just HH so you can distinguish between AM and PM.
If it is a date you need:
...
date_transaction between to_date('2016/01/01', 'YYYY/MM/DD')
and to_date('2016/02/29', 'YYYY/MM/DD')
...

Mysql between dates is not working

I'm writing the below query to get records between two dates. I'm using Mysql version 5.5. May its duplicate exactly I didn't know. But no answer working for me so that I'm asking. I'm following least date after latest date. Even though its not working.
Problem: Empty resultset.
pstmt=con.prepareStatement("SELECT urlid FROM youtubevideos WHERE lastwatched >=? AND lastwatched <=? order by id desc LIMIT 8");
pstmt.setString(1,previousdate);//14-05-2015
pstmt.setString(2,currentdate);//12-08-2015
rs=pstmt.executeQuery();
while(rs.next())
{
.........
}
But I'm getting empty resultset.
My table youtubevideos contains records
urlid lastwatched
-------------------
url1 12-08-2015
url2 11-08-2015
url3 08-05-2015
url4
url5 10-08-2015
Above is some data. Here lastwatched is of varchar and lastwatched is empty for some records. If my previous date 08-05-2015 means less than the current day (12) then above query working. Otherwise (from 13-05-2015 onwards) its not working. Any suggestions please.
You are using wrong date format for sql:
12-08-2015 // this is the output format
use yyyy-MM-dd instead:
2015-08-12 // this is the sql store format
This query works great in my Mysql database:
SELECT * FROM your_table where DATE <= "2015-05-08" AND DATE >= "2015-08-12"
To convert your strings:
Date initDate = new SimpleDateFormat("dd-MM-yyyy").parse(date);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String parsedDate = formatter.format(initDate);
Here lastwatched is of varchar
The issue is that you are storing date fields as type VARCHAR. This would work if your date format was Y-m-d since sorting this alphabetically is the same as sorting by date.
I recommend you change the lastwatched column to be a date type, this will allow the BETWEEN to work correctly and will also provide access to the date functions in MySQL.
Fix the data in the table. You should not be storing bona fide dates as varchar(). MySQL has a great data type for them, called date (or perhaps datetime.
Here is one method:
alter table youtubevideos add column NEW_lastwatched date;
update youtubevideos
set NEW_lastwatched = str_to_date(lastwatched, '%d-%m-%Y');
alter table drop column lastwatched;
alter table rename column NEW_lastwatched lastwatched date;
Then, pass in your parameters in the ISO standard format 'YYYY-MM-DD' and your problems with dates using this column will be fixed.

Using timestamp with mysql and java

I'm trying to save a timestamp to a table in mySQL but whenever I look at the results it just shows 0000-00-00 00:00:00.
I assume I'm not using the timestamp right but anyways in my table I have a column named time and its property is TIMESTAMP
In my Java I have:
java.sql.Timestamp timestamp = new java.sql.Timestamp(0);
String query = "insert ignore into time(time_now) values (?)";
pstmt.setString(1, timestamp);
pstmt.executeUpdate();
My database connection is fine as I have a lot of other information that's being uploaded to it with no problem, I'm just having trouble with the timestamp
Something like this should work:
java.util.Date date = new java.util.Date();
Timestamp timestamp = new Timestamp(date.getTime());
preparedStatement = connection.prepareStatement("insert ignore into time(time_now) values (?)");
preparedStatement.setTimestamp(1, timestamp);
If you only want to store the time then use the TIME data type instead and to insert the current time of the SQL server use CURTIME() like this
insert into your_table (time_column)
values (curtime())
Take a look at java.sql.Timestamp. You are instantiating a new Timestamp object with '0'.

java mysql select statement not returning full date

I'm a java newbie but I'm not sure what I'm doing wrong. When I try to retrieve the last two dates from a database it only displays the year(while in mysql the same command provides the correct result).
Mysql command: SELECT DISTINCT date From fundanalysis ORDER BY date DESC LIMIT 2
Expected result:
2011-06-13
2011-06-08
Here's my java code:
preparedStatement = con.prepareStatement("SELECT DISTINCT date From fundanalysis ORDER BY date DESC LIMIT 2");
ResultSet numberofrowsresultset = preparedStatement.executeQuery();
numberofrowsresultset.next();
// most recent date
currentdate.add(numberofrowsresultset.getInt("date"));
System.out.print(numberofrowsresultset.getInt("date"));
numberofrowsresultset.next();
// last date before most recent
currentdate.add(numberofrowsresultset.getInt("date"));
return currentdate;
The final result is: [2011, 2011]
I basically want the exact same result as I get when I run the mysql query because I have to submit it as is to do another query later in the program.
pls help!
it is .getDate not .getInt
try:
numberofrowsresultset.getDate("date");
Try use .getDate() instead of .getInt():
currentdate.add(numberofrowsresultset.getDate("date"));
You are using .getInt which returns a numerical value. You need to use .getDate instead when you are getting a date value:
System.out.print(numberofrowsresultset.getDate("date"));
^^^^ change Int to Date
Date is not an integer so your '.getInt("date")' method is not returning the result you expect.
You need
java.sql.Date myDate = numberofrowsresultset.getDate("date");

Categories