Use date in MapSqlParameterSource in java Spring - java

I want to fetch result between start_date to end_date so that i can find my product report.
sql = new StringBuilder()
.append(" select oi.last_modified,oi.product_key")
.append(" from orders o join order_item oi ")
.append(" on oi.id_order = o.id ");
.append(" AND o.created between '")
.append(":start_date") // line - 1
.append("' and '")
.append(":to_date"); // line - 2
in both lines (line-1 & line-2)
I am trying to use prevention technique for that i am using
MapSqlParameterSource namedParams = new MapSqlParameterSource();
so for achieving this i tried lots of combination but no luck.
namedParams.addValue("start_date","start_date",Types.TIMESTAMP);
namedParams.addValue("to_date","to_date",Types.VARCHAR);
I am getting different error for different try.
i.e.
java.util.Date cannot be cast to java.sql.Date
invalid input syntax for type timestamp with time zone

I think it also depends on the data type of your database field. In MySQL for example there are date, datetime and timestamp.
For me having a MySQL datetime and working with a java.util.Date object creating a java.sql.Date and specifying the Types.TIMESTAMP worked (startDate being the java.util.Date object):
MapSqlParameterSource namedParams = new MapSqlParameterSource();
namedParams.addValue("start_date", new java.sql.Date(startDate.getTime()), Types.TIMESTAMP);

I removed single quote and it works for me.
dynamicColumnsQuery = new StringBuilder();
dynamicColumnsQuery.append("SELECT concat(TO_CHAR(months, 'MonYY'),' Adverts') AS monthYear FROM generate_series( CAST(:fromDate");
dynamicColumnsQuery.append(" as DATE) , CAST(:toDate");
dynamicColumnsQuery.append(" as DATE) , '1 month' ) AS months");

Related

JPA Query for fomat Date

In Data base , createdDt is storing formated like:
15-01-20 10:43:20.394000000 AM
I am passing "created" as dd-mm-yyyy
I want to take the matching date from the table(without comparing time)
#Query("SELECT p FROM ABC p WHERE ( COALESCE(:created) is null or p.createdDt = :created) order by p.createdDt desc")
List<ABC> filterABC(#Param("created") Date created);
How to parse the date within query ?
You could try to use native query using specific DBMS stuff to extract date part.
#Query(value = "SELECT * from ABC where DATE_FORMAT(createdDt, '%d-%m-%Y') = ?1", nativeQuery = true)
List<ABC> filterABC(Date created);
DATE_FORMAT is MySQL specific function. Use the appropriate date function in accordance with your DBMS

Postgres overlapping symbol not running in java

I have a query to test two dates against two timestamp columns in the table if they overlap or not.
Query is working fine in the database client but when i added it in my java code it fails with an exception error.
I need to know how to format the && symbols in the query to be able to work.
SELECT count(*)
FROM attendance_jobs
WHERE tsrange( start_date, end_date) && tsrange(TIMESTAMP '2019-04-22', TIMESTAMP '2019-03-22 ')
Here is my java code:
long count = jdbi.withHandle(handle -> {
return handle.createQuery("select count(*) from attendance_jobs where tsrange(start_date, end_date) && tsrange(timestamp :start_date, timestamp :end_date)")
.bind("start_date", start_date)
.bind("end_date", end_date)
.mapTo(Long.class)
.findOnly();
});
The start_date and end_date data type is Timestamp.
org.jdbi.v3.core.statement.UnableToExecuteStatementException: org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"
This is just guesswork, but I think you should have a look at the usage of :start_date and :end_date again:
If start_date and end_date (java variables) are of type Timestamp you should remove the timestamp prefix to :start_date and :end_date in the query. As the documentation says, the java type Timestamp is supported by jdbi:
Out of the box, Jdbi supports the following types as SQL statement arguments:
* ...
* java.sql: Blob, Clob, Date, Time, and Timestamp
* ...
So my guess is that you have to use the query like this:
long count = jdbi.withHandle(handle -> {
return handle.createQuery("select count(*) from attendance_jobs where tsrange(start_date, end_date) && tsrange(:start_date, :end_date)")
.bind("start_date", start_date)
.bind("end_date", end_date)
.mapTo(Long.class)
.findOnly();
});
Also, but this may be personal taste, I recommend to use different spelling of bind variables and database columns. The latter with underscores (as you did), the other in camel case so it is less confusing if you use similar names. Also, it is uncommon to use underscores in java variables, so the code would look similar to this in my spelling:
Timestamp startDate = ...;
Timestamp endDate = ...;
String queryString = "select count(*) from attendance_jobs "
+ "where tsrange(start_date, end_date) && tsrange(:startDate, :endDate)";
long count = jdbi.withHandle(handle -> {
return handle.createQuery(queryString)
.bind("startDate", startDate)
.bind("endDate", endDate)
.mapTo(Long.class)
.findOnly();
});

To Check whether a date is between two dates in column in MongoDB using JAVA

I am working on web-services by using java with MongoDB, in that i am trying to check whether a date time say "2015-04-16 16:32:49" lies between the date time present in the fields start_time and end_time from table.In mysql i tried the following query
select * from tablename where Employee_id =101 and '2015-04-16
16:32:49' between start_time and end_time;
i am trying to replicate the same using java in MongoDB by using following code
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("employeeID", "101");
String date = "2015-04-17 11:02:49";
whereQuery.put(date, new BasicDBObject("$gt", "start_time ")
.append("$lt", "end_time "));
DBCursor cursor = col.find(whereQuery);
but the code is not working, it is not comparing the date specified with the two column in table,what is the right syntax to do that
if i try this code
whereQuery.put(someOtherField, new BasicDBObject("$gt", "2015-04-17 11:02:49")
.append("$lt", "2015-04-19 11:02:49"));
it is working i need the syntax to compare a date String with two fields in entire table
Your query roughly translates to:
select * from tablename where Employee_id =101 and '2015-04-16 16:32:49' > "start_time" and '2015-04-16 16:32:49' < "end_time";
You are comparing string "start_time" and "end_time" with '2015-04-16 16:32:49'.
Correct query would be:-
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("employeeID", "101");
String date_string = "2015-04-17 11:02:49";
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
Date date = format.parse(date_string);
whereQuery.put("start_time", new BasicDBObject("$lt", date));
whereQuery.put("end_time", new BasicDBObject("$gt", date));
DBCursor cursor = col.find(whereQuery);
You can use a regular JAVA date object.

mongodb + java + iso date search

In my mongo db database i have column like this.
"created_on" : ISODate("2014-07-02T01:38:48.713Z");
In order to to search this column am giving the following query:
db.XYZ.find({ "created_on" : ISODate("2014-07-02T01:38:48.713Z")})
Now i want to use java for retrieving this data from database:
My query is like:
DateTime dateTime = new DateTime( "2014-07-02T01:38:48.713Z" );
BasicDBObject query1 = new BasicDBObject("created_on", dateTime);
DBCursor cursor = table.find(query);
but am not getting anything query is returning 0 rows??
Any body please help how to set iso date from java.
The mongodb driver does not work with DateTime currently. You have to use java.util.Date

How to write like query for date in java

Here I am going to get data based on date only but my data continence both date and time here I am using like query to select that data based on date but I am not getting it can any plz exp line it thanks.
String device = "NR09G05635";
String date = "2013-11-29";
java.util.Date temp = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse(date);
java.sql.Date date1 = new java.sql.Date(temp.getTime());
sql = "select * from gpsdata1 where deviceId=? and dateTime like '" + date1 + "'";
System.out.println("sql" + sql);
ps1 = con.prepareStatement(sql);
ps1.setMaxRows(1);
ps1.setString(1, device);
ps1.execute();
rs = ps1.getResultSet();
-You use the LIKE operator to compare a character, string, or CLOB value to a pattern. Case is significant. LIKE returns the BOOLEAN value TRUE if the patterns match or FALSE if they do not match
Use TO_CHAR to explicitly create a string based on a DATE, using the format you want. Don't rely on implicit conversions.
Select *
From gpsdata1
Where NVL ( TO_CHAR ( dateTime
, 'YYYY-MM-DD HH:MI:SS AM'
)
, ' ' -- One space
) Like '%';
SELECT * FROM gpsdata1
WHERE deviceId=? and CONVERT(VARCHAR(25), dateTime, 126) LIKE '2013-11-19%'
LIKE operator does not work against DATETIME variables, but you can cast the DATETIME to a VARCHAR

Categories

Resources