Can't retrieve correct time from database - java

I have fields startTime and endTime in my table with type as time. When I try to retrieve it with query it gives wrong values of time even if the data table values are correct.
The query is as follows :
SELECT
ts.id,
ts.serviceRuleId,
FROM_UNIXTIME(ts.startTime, '%h %i %p') AS tempStrtTime,
FROM_UNIXTIME(ts.endTime, '%h %i %p') AS tempEndTime,
ts.createdBy,
ts.createdOn,
ts.startDate,
ts.endDate
FROM
TemporaryTimeSlots AS ts
GROUP BY
ts.id

Why are you using the FROM_UNIXTIME etc.
You are using Java, so use the SQL.Date object and you will get the correct result
select ts.id, ts.serviceRuleId,ts.startTime as tempStrtTime, ts.endTime as tempEndTime, ts.createdBy, ts.createdOn, ts.startDate, ts.endDate from TemporaryTimeSlots as ts group by ts.id

Related

How to set java.sql.Timestamp in prepared statement when used for TIMESTAMPDIFF calculation?

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 = ?"

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.

Returning records from database between two dates

I've created a program using Java that connects to a database and allows the user to submit a record. This record includes a unique reference number and started date (Variable: StartedDate).
I want to enable the user to search for the amount of cases submitted between two dates (the first day of the month and todays date).
So far I have the SQL query
select * from cases where StartDate>'***' and Date<'****'
In Java, it would be
select * from cases where StartedDate>'1stMONTHDATE' and Date<'TODAYSDATE'
My first question is - Within the database, there isn't a field called "Date" as this would have to change on a daily basis. How would I reference this to be the automatically generated date from Java?
Also, how would I implement the Count() method to return an int of the number of records returned?
SELECT * FROM cases WHERE StartedDate BETWEEN :startDate AND :endDate
In JPQL:
public List<Cases> findAllEvents(Date startDate, Date endDate) {
List<Cases> allCases = entityManager.createQuery("SELECT * FROM cases WHERE StartedDate BETWEEN :startDate AND :endDate")
.setParameter("startDate", startDate, TemporalType.DATE)
.setParameter("endDate", endDate, TemporalType.DATE)
.getResultList();
return allCases ;
}
Well i suppose by "Date" in the query you mean end date.
if that is so you can calculate the end date with either of the two following methods
java using the Calender class and pass the end date as parameter to the query
In the sql by modifying the query like
for ex- here the end date is one month from start date.This is DB specific.This will work in Postgres. Look for the correct syntax according to the DB you use to get the end date
select * from cases where StartedDate>'1stMONTHDATE' and ('StartedDate' + INTERVAL '1 MONTH')<'TODAYSDATE'.
Regarding the count()-A simple SELECT Count(*) will give you the number of rows returned by thw query
If you are using MSSQL and your date values are as String then you can use following query:
SELECT c FROM cases c where CONVERT(VARCHAR(10),StartDate,121) between :startDate AND :endDate
I am using this query in my application with mssql server

Set timestamp in Oracle

I use Prepared statements in Oracle SQL query. I have problem which I don't know how to solve.
I want to set timestamp like using this:
ps.setTimestamp(36, null);
The problem is that I don't know what parameter to set in order to execute timestamp into Oracle? How I must replace null in my case?
This example sets a Timestamp value to the current time (with precision to milliseconds):
Timestamp ts = new Timestamp(new Date().getTime());
ps.setTimestamp(36, ts);
If you also need nanoseconds you can set those separately:
Timestamp ts = new Timestamp(new Date().getTime());
ts.setNanos(12345);
ps.setTimestamp(36, ts);
If you look at the method in the PreparedStatement class, you need to create a TimeStamp object that you will replace your null with.

how to get the timestamp taken to insert the data into a table

I am storing images in a table i would like to get the time stamp taken to insert the image into the table are their any inbound sql syntax for getting the timestamp of inserted data ? or any java syntax for getting the timestamp of inserted data from the database kindly help out
CURRENT_TIMESTAMP is a function that is available in most database servers. So a sql like this should work.
INSERT INTO <some_table> (<timestamp_column_name> VALUES (CURRENT_TIMESTAMP)
If you want to do it in java then you can do the following:-
java.util.Date currentTime = new java.util.Date();
System.out.println(new java.sql.Timestamp(currentTime.getTime())); //gets you the current sql timestamp
It is going to vary by database. This is going to work in both least Oracle and mysql:
insert into PRODUCE (color, weight, added_at) values ('red', '8 ounces', sysdate());
If you are using MySql, you can also add DEFAULT CURRENT TIMESTAMP to your column definition:
create table PRODUCE (
color varchar(20),
weight varchar(20),
added_at TIMESTAMP DEFAULT CURRENT TIMESTAMP
);
insert into PRODUCE (color, weight) values ('red', '8 ounces');
In Oracle, a separate trigger would need to be created to achieve the default value.

Categories