Here is the scenario:
I have a sample SQL query like:
SELECT ID, NAME FROM MYTABLE WHERE DATE = &Date
I wanted to replace this &Date at run time based on certain conditions. So I have a utility class which provides the actual Timestamp.
Timestamp timeStamp = Util.getTimeStamp("16102014 03:40:06")
Problem is while I am trying to replace it. If I replace it as a timeStamp.toString() [Not the right way to do it, just for testing I did], its getting replaced but my query became Invalid and I am getting SQL exception (ORA-01861: literal does not match format string).
What I wanted to achieve is I want to replace the place holder with timestamp value and execute the query.
Constraints
I can not use PreparedStatement set values as the query can be any arbitary query and I do not have prior information about the clause.
Any help is appreciated.
Since we are in "String" land, this is a "String" solution:
Timestamp timeStamp = Util.getTimeStamp("16102014 03:40:06")
SimpleDateFormat format = new SimpleDateFormat("''yyyy-MM-dd HH:mm:ss''");
String formattedDate = format.format(timeStamp);
sql = sql.replace("&Date", formattedDate);
Note: The double '' in the date format means produce a single quote in the output (a single quote is the delimiter for literal text in a date format).
Note also that because you're not using a driver, the character used to quote the text is database-dependant. This solution assumes that a single quote may be used for quoting a literal, but if your database requires a double quote ", the format should be "\"yyyy-MM-dd HH:mm:ss\"",
I think it should be like this
SELECT ID, NAME
FROM MYTABLE
WHERE DATE = TO_TIMESTAMP(&Date, 'yyyy-mm-dd hh:mm:ss.fffffffff')
Related
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.
I am currently facing the following issue:
I want to get the time difference in seconds between the current time and the given timestamp in a prepared statement.
public List<Foo> getFoos(String id, Timestamp ts) {
return jdbcTemplate.query(
"SELECT TIMESTAMPDIFF(2, (CURRENT TIMESTAMP - ?)) AS NEW_TIMESTAMP FROM SCHEMA.TABLE WHERE ID = ?",
new Object[]{ts, id},
(rs, rowNum) -> mapFooFromResultSet());
}
This query will fail with
com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-402, SQLSTATE=42819, SQLERRMC=-, DRIVER=
-402 AN ARITHMETIC FUNCTION OR OPERATOR function-operator IS APPLIED TO CHARACTER OR DATETIME DATA
I am using a DB2 database and cannot switch to any other db driver.
So my question would be how do I achieve the time difference in a sql statement between the current time and a given java.sql.Timestamp value?
Thank you in advance for your help.
It seems that the function TIMESTAMPDIFF does not accept a Timestamp, but expects a String value like specified in the string-expression paragraph of the docs. In the examples they make use of the CAST, CHAR and TIMESTAMP functions, so the following might solve the problem.
Instead of a Timestamp object, a corresponding String value needs to be specified in the format YYYY-MM-DD-hh.mm.ss:
SELECT TIMESTAMPDIFF(2, CHAR(CURRENT TIMESTAMP - TIMESTAMP(?))) AS NEW_TIMESTAMP
FROM SCHEMA.TABLE
WHERE ID = ?
As mentioned by #Idz the TIMESTAMPDIFF expects a string-expression. Look at the last example on the provided website you will see a solution.
For my example it works with the following code:
"SELECT TIMESTAMPDIFF(2, CAST(CURRENT_TIMESTAMP - CAST(? AS TIMESTAMP) AS CHAR(22))) AS NEW_TIMESTAMP FROM SCHEMA.TABLE WHERE ID = ?"
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')
...
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.
I am running the following query to get time difference of two times
resultSet = statement.executeQuery("SELECT TIMEDIFF('14:03:55.256', '14:02:51.780') AS td");
MySQL gives time difference in this format
00:01:03.476
But both
resultSet.getTime("td"); and resultSet.getObject("td");
returns 00:01:03
According to the documentation getTime(String string) retrieves the value of the designated column in the current row of this ResultSet object as a java.sql.Time object in the Java programming language.
java.sql.Time corresponds to SQL TIME and contains information about hour, minutes, seconds and milliseconds.Then why am I getting 00:01:03 instead of 00:01:03:476?
What I basically want is to store 00:01:03.476 into a String. Is there any workaround or I am doing it wrong?
If you are verifying the result by printing it out note that java.sql.Time.toString() only returns a string in the format hh:mm:ss
You should really use rs.getTimestamp which will return a java.sql.Timestamp
Try to do this:
String s = new SimpleDateFormat("HH.mm.ss.SSS").format(t.getTime());
where t is your variable of type java.sql.Time.
Hope this will solve you problem.