I need help converting some sql to hibernate sql.
SQL:
String sql = "select time, hour(time) as hour, minute(time) as minute "
+ "from db where time >= DATE_ADD(now(), INTERVAL -24 HOUR) "
+ "group by 2 order by time LIMIT 500";
I use SQLQuery to add scalars. I tried this for HQL:
String hql = "select time, hour(time), minute(time) from db as O "
+ "where O.time >= :time group by 2 order by O.time";
Query query = session.createQuery(hql);
query.setDate("time", calend.getTime()); //calend is a Calendar object
However, this doesn't work. Error says it's an hql error.
Instead of using setDate try using setParameter.
From this link about HQL dates:
"setDate" will truncate the HQL date value and ignore the hours, minutes, seconds.
Using setParameter will interpret the values as the parameter that you indicated by :variable.
Related
I am using PHP with MySQL and would like to select rows that have a booking time within 2 hours from now. How do I compare what is in my database with the NOW() MySQL function?
I have columns pickupDate in the format yyyy-mm-dd and pickupTime in the format HH:mm (24-hour). I have tried creating a query with NOW() which returns the a 12-hour time as HH:mm:ss e.g. 2019-05-24 07:54:06 . I can't figure out how to format this to 19:54, or if I should use a different function instead.
For example, if the current date and time is 24/05/19 19:54:06, I would like to select rows between 19:54 and 21:54 on this date.
My table structure is:
referenceNo VARCHAR(100)
pickupDate DATE
pickupTime VARCHAR(100)
You need to create a DATETIME compatible value out of your pickupDate and pickupTime (which you can do by CONCATing them together), then you can compare that with a time range from NOW() to 2 hours later:
SELECT *
FROM yourtable
WHERE CONCAT(pickupDate, ' ', pickupTime) BETWEEN NOW() AND NOW() + INTERVAL 2 HOUR
Demo on dbfiddle
To add two hours in php
$hoursnow = date('H:i');
$timestamp = strtotime(date('H:i')) + 60*60*2;
$plusTwohours = date('H:i', $timestamp);
And $PlusTwohours using this variable frame the query like below
Sql Query:
$sqlQuery = 'select * from foodorder where pickupDate=DATE(NOW()) AND pickupTime>='.$hoursnow.' and pickupTime<='.$plusTwohours;
$result = mysql_query($sqlQuery);
variable $result will have the values of query
For Second Scenario: Adding hours to end of the day May 24 23:30:00
This should be handle by two different date for same column pickupDate
$d = new DateTime('2011-01-01 23:30:30');
$startDate = $d->format('Y-m-d H:i:s'); // For testing purpose assigned manually
$starttime = date('H:i');
// Here Process start, storing end date by adding two hours
$enddate1 = strtotime($startDate) + 60*60*2;
$enddate = date('Y-m-d', $enddate1); // Extracting date alone
$endtime = date('H:i', $enddate1); // Extracting time alone
Have to compare start and end date for column pickupDate, here is the query
$sqlQuery = "select * from foodorder where pickupDate>=DATE(".$startDate.") AND pickupDate<=DATE(".$enddate.") AND pickupTime>='".$starttime."' AND pickupTime<='".$endtime."'";
$result = mysql_query($sqlQuery);
Describe:
I have a table with timestamp column and i want to get the number of values where the timestamp in specific time window.
My code is as shown in here:
String startTime = "2018-08-08 00:00:00";
String endTime = "2018-08-08 23:59:59";
productDF.where("CREATETIME >= '" + startTime + "' AND CREATETIME <= '" + endTime + "'").count();
I also tried between...and...sentence; and also:
productDF.where(unix_timestamp(col("CREATETIME"), "yyyy-mm-dd hh:mm:ss")
.cast("timestamp")
.between(
Timestamp.valueOf(startTime),
Timestamp.valueOf(endTime)
)).count();
The result i get is 6843.
But when i operate the sql sentence using Navicat:
SELECT COUNT(*) FROM my_table
WHERE CREATETIME BETWEEN '2018-08-08 00:00:00' and '2018-08-08 23:59:59';
it shows 7689.
Problem:
I want to know why i get the different results in Spark and Mysql.....what am i missing here??
Problem solved!
The problem happened because of the TIMEZONE.
In spark env., it get the timezone from_unixtime..So need to set the config.
.config("spark.sql.session.timeZone", "UTC")
But I still don't understand why the spark sql session flow the system timezone instead of just select from the column.....
I am using HQL with DATE_ADD (mysql function) as below
String hql =
"select count(*) " +
"from ProgramGroupEvent as eventLog " +
"where eventLog.id= :id" +
"and DATE_ADD( eventLog.eventDate, INTERVAL :interval MINUTE) > now()";
long count = 0;
try {
count = ((Long)sess.createQuery( hql )
.setLong( "id", id)
.setInteger("interval", interval )
.iterate().next()).longValue();
} catch (HibernateException e) {
e.printStackTrace();
}
But hibernate throws a token error as below
antlr.NoViableAltException: unexpected token: :
at org.hibernate.hql.internal.antlr.HqlBaseParser.identPrimary(HqlBaseParser.java:4016) ~[hibernate-core-4.1.7.Final.jar:4.1.7.Final]
at org.hibernate.hql.internal.antlr.HqlBaseParser.primaryExpression(HqlBaseParser.java:859) ~[hibernate-core-4.1.7.Final.jar:4.1.7.Final]
at org.hibernate.hql.internal.antlr.HqlBaseParser.atom(HqlBaseParser.java:3390) ~[hibernate-core-4.1.7.Final.jar:4.1.7.Final]
PS: I am using Hibernate 4.1.7
I did further research and found out the issue. The problem is Hibernate is not able parse the syntax. As per it's expectation, this is not well formed HQL syntax.
https://forum.hibernate.org/viewtopic.php?f=1&t=982317&view=previous
I fixed by replacing
DATE_ADD( eventLog.eventDate, INTERVAL :interval MINUTE) > now()";
With
time_to_sec(timediff( now() , eventLog.eventDate )) < :seconds";
Hopefully, this can help for someone
Your query require two parametrs
pharmacyOid
interval
But in your query parameters id and interval are used.
Your query should look:
count = ((Long)sess.createQuery( hql )
.setLong( "pharmacyOid", id)
.setInteger("interval", interval )
.iterate().next()).longValue();
I am trying to run a query in java that uses a java.sql.Timestamp object as the date to compare with in the where clause.
Here is how the query string that is built in Java
String getTransactionsSQL = "Select transaction_seq " +
"From transactions ct " +
"Where id = 'ABCD'" +
"And ct.out_msg_timestamp" +
"<= to_date('" + parseDate.getTimeStamp() +"','YYYY-MM-DD HH:MI:SS..')" +
"order by transaction_seq";
The statement parseDate.getTimeStamp() returns a java.sql.TimeStamp object that contains a date. Here is an example output of System.out.println(parseDate.getTimeStamp());
2011-03-07 05:47:57.0
When i run the above query i get this error
java.sql.SQLException: ORA-01843: not a valid month
Any clues?
Use PreparedStatement: http://download.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html
Never use string concatenation to pass arguements to SQL commands (security risk: SQL injection)!
i am working on a part of my system called Patient Record Management system and in it there is an Appointment Management, and in Appointment you make a timeslot unavailable to others once occupied so here lies the problem:
there are 3 columns that are in my database: date(Date), TimeIn(Time), TimeOut(Time)
this is what i've done so far:
sqlQuery = "SELECT * FROM appointment where date = '" & datePicker.Value.ToString("dd-MM-yyyy") & "' and TimeIn <= CAST('" & timeinPicker.value.ToString("HH:mm") & "' AS Time) and TimeOut >= CAST('" & timeoutPicker.value.ToString("HH:mm") & "' AS Time)"
example if i put 12:00 to timeinPicker and 13:00 to timeoutPicker, all time between 12:00 and 13:00 should be selected, but my problem is it won't get selected, it can only select it if i input exactly 12:00 and 13:00 but when i put 12:01 and 12:59, the sql cant select it like it didnt exist
is there some way to select them so i can know which time is occupied.
P.S. i'm using MySql
if you are using java means replace & character with + and try
sqlQuery = "SELECT * FROM appointment where date = '" + datePicker.Value.ToString("dd-MM-yyyy") + "' and TimeIn <= CAST('" + timeinPicker.value.ToString("HH:mm") + "' AS Timein) and TimeOut >= CAST('" + timeoutPicker.value.ToString("HH:mm") + "' AS Timeout)";
First thing is you should use the parameterized queries always that give you protection from the Sql Injection.
You can change your query like this,
string query = "SELECT * FROM appointment where date = #DateValue and TimeIn <= CAST(#TimeInValue AS Time) and TimeOut >= CAST(#TimeOutValue AS Time)"
And then set the Paramters values to following values using the AddParamter() I don't know which programming language you are using so there will be similar method to add the parameter use that,
#DateValue = datePicker.Value.ToString("dd-MM-yyyy")
#TimeOutValue = timeoutPicker.value.ToString("HH:mm")
#TimeInValue = timeInPicker.value.ToString("HH:mm")