input date using jdbc to hsqldb - jdbc

How do i get all the rows having endDate greater than current date? do i have to use setString() or setDate()? they are both not working!!!
What is the correct way to do it?
ResultSet is empty but database contains data for the given sql statement
public ArrayList<AddBean> listPendingTasks() {
java.util.Date date = new java.util.Date();
String modifiedDate= new SimpleDateFormat("yyyy-MM-dd").format(date);
Connection con = JDBCHelper.getConnection();
PreparedStatement ps_sel = null;
ArrayList<AddBean> c = new ArrayList<AddBean>();
ResultSet rs = null;
try {
ps_sel = con.prepareStatement("select * from tasks where enddate > ? order by enddate");
ps_sel.setString(2, modifiedDate);
ps_sel.execute();
rs = ps_sel.getResultSet();
while(rs.next())
{
AddBean ab = new AddBean();
ab.setTname(rs.getString(2));
ab.setCategory(rs.getString(3));
ab.setStartdate(rs.getString(4));
ab.setEnddate(rs.getString(5));
ab.setDescription(rs.getString(6));
ab.setPriority(rs.getString(7));
c.add(ab);
}
return c;
} catch (SQLException e) {
e.printStackTrace();
return null;
}

try this
If your table has a column of type DATE:
Query : SELECT * FROM [values] v WHERE date >= '2013-06-03';
Then use this method java.sql.Date.valueOf(java.lang.String)
ps.setDate(2, java.sql.Date.valueOf("2015-09-13"));
Updated with Date and Time Types:
The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'. MySQL retrieves and displays TIME values in 'HH:MM:SS' format. TIME values may range from '-838:59:59' to '838:59:59'.
String QUERY = "UPDATE TABLE_NAME SET dateValue=?, timeValue=?, timeStampText=? WHERE rowIdentify=?";
PreparedStatement pstmt = con.prepareStatement( QUERY );
pstmt.setDate(1, java.sql.Date.valueOf( localDate )); // DATE Type
pstmt.setTime(2, java.sql.Time.valueOf( localTime )); // TIME Type
pstmt.setString(3, localDateTime ); // TEXT Type
pstmt.setString(4, conditionValue );
Sample code to get the above Date fields value. getDateFromEpochTime()
long startTime=System.currentTimeMillis();
String str = getDateFromEpochTime(startTime);
CharSequence charSequence = str.subSequence(0, str.length());
String pattern = "yyyy-MM-dd HH:mm:ss";
DateTimeFormatter dateTimeFormatter = java.time.format.DateTimeFormatter.ofPattern( pattern );
LocalDate localDate = java.time.LocalDate.parse( charSequence, dateTimeFormatter );
LocalTime localTime = java.time.LocalTime.parse( charSequence, dateTimeFormatter );
LocalDateTime localDateTime = LocalDateTime.parse( charSequence, dateTimeFormatter);
Java SQL driver doesnot support java.sql.Timestamp for DATETIME or TIMESTAMP type of Table column. Try to use PreparedStatement when query contains Date and Time Types types.

learn the date format of the db. hsql db supports 'yyyy-mm-dd'. If you are using prepared statements, then you can input date as a String or a date. that is not going to make a difference. I recommend using string. Using date is a little complicated for beginners because its not util date. Its sql date. Date formats can sometime be troublesome.

Related

how to convert HAC flexible query to DAO query

I'm using below flexible query in HMC and it's working fine.
The same query needs to convert the DAO layer and input is a data parameter.
Please any help on this?
SELECT * FROM {Product} WHERE {creationtime} >= TO_DATE('2020/02/19','YYYY/MM/DD')
The complete and definitive guide for the creation of Flexiqueries and corresponding DAO code.
Refer DefaultProductDao and create one for your requirement or you can extend it if you want to reuse any function. I hope by looking at the class, you'll have an understanding of how to write and execute the flexi query in the SAP Hybris.
Converting your query to DAO
Here, I would suggest avoiding using TO_DATE or any DB function to ensure that the query is not DB dependent. In your case, you can parse string date to Java Date object and pass it to the query something like below
String query = "SELECT * FROM {"+ ProductModel._TYPECODE +"} WHERE {"+ ProductModel.CREATIONTIME +"} >= ?"+ProductModel.CREATIONTIME;
final FlexibleSearchQuery searchQuery = new FlexibleSearchQuery(query);
final Map<String, Object> params = new HashMap<String, Object>();
params.put(ProductModel.CREATIONTIME, getDateObject("2020/02/19"));
searchQuery.addQueryParameters(params);
final SearchResult searchResult = getFlexibleSearchService().search(searchQuery);
return searchResult.getResult();
Method
private Date getDateObject(String date)
{
// logic to parse your string date (YYYY/MM/DD) to java Date object
return new Date(); //return your parsed date object here
}

How do I get my hour, minutes, seconds, and milliseconds to be zeros?

I'm trying to get my format to be 2016-07-08T00:00:00.000Z.
String myDate = "20160708";
LocalDate myLocalDate = LocalDate.parse(myDate, DateTimeFormatter.BASIC_ISO_DATE);
OffsetDateTime myOffsetDate = myLocalDate.atTime(OffsetTime.now(ZoneOffset.UTC));
System.out.println(myOffsetDate); //2016-07-08T14:58:23.170Z
Well don't say "I want it to use the current time"! That's what this is doing:
OffsetTime.now(ZoneOffset.UTC)
If you just want an OffsetDateTime from a LocalDate by providing a zero offset and midnight, you can use:
OffsetDateTime myOffsetDate = myLocalDate
.atTime(LocalTime.MIDNIGHT)
.atOffset(ZoneOffset.UTC);
Or if you prefer:
OffsetDateTime myOffsetDate = myLocalDate
.atTime(OffsetTime.of(LocalTime.MIDNIGHT, ZoneOffset.UTC));
(Personally I prefer the first version, myself...)
Note that that's just getting you the right OffsetDateTime. If you want to format that with milliseconds and seconds, you'll need to do that explicitly:
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX");
System.out.println(myOffsetDate.format(formatter));
As noted in comments, if you're find with a ZonedDateTime instead of an OffsetDateTime, you can use
ZonedDateTime myOffsetDate = myLocalDate.atStartOfDay(ZoneOffset.UTC);
I am not quite sure if you can get the ISO_INSTANCE date format with the given string using LocalDate. but you can use below java 8 piece of code to get the required format.
public String getISO_8601DateFormat(String yyyyMMdd){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String requiredFormat = null;
try {
Date inputDate = sdf.parse(yyyyMMdd);
long dateLongRepresentation = inputDate.getTime();
long myTimeZoneOffset = TimeZone.getTimeZone(ZoneId.systemDefault()).getOffset(inputDate.getTime());
Instant instance = Instant.ofEpochMilli(dateLongRepresentation + myTimeZoneOffset);
requiredFormat = instance.toString();
} catch (ParseException e) {
e.printStackTrace();
}
return requiredFormat;
}
Enjoy coding with java :)

HQL to query records between two dates

I am trying to query all customers records using HQL in my Spring/ Hibernate app that have DateAdded between Date1 and Date2 OR LastSeen between Date1 and Date2, so I've build this HQL query in the Repository/ DAO class:
sessionfactory.getCurrentSession().createQuery("from Customer c where c.dateAdded BETWEEN '"+startDate+"' AND '"+endDate+"' OR c.lastSeenDate BETWEEN '"+startDate+"' AND '"+endDate+"'").list();
I've debugged the app to check the startDate and endDate and found that they are sent as:
startDate: Wed Jan 22 01:16:57 HKT 2014
endDate: Wed Jan 29 01:16:57 HKT 2014
In DB, I am 100% sure there is one record at least meeting this query, as this record DateAdded and LastSeen are as follows:
2014-01-23 15:33:38
2014-01-25 15:33:38
So can someone please tell me what I am doing wrong / missing here?
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String frmDate = format.parse(startDate);
String enDate = format.parse(endDate);
sessionfactory.getCurrentSession()
.createQuery("FROM Customer AS c WHERE c.dateAdded BETWEEN :stDate AND :edDate ")
.setParameter("stDate", frmDate)
.setParameter("edDate", enDate)
.list();
hope this will help!
This is an old post, but I figured it might help someone. Setting .setTimeStamp should do the trick.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String frmDate = format.parse(startDate);
String enDate = format.parse(endDate);
sessionfactory.getCurrentSession()
.createQuery("FROM Customer AS c WHERE c.dateAdded BETWEEN :stDate AND :edDate ")
.setTimestamp("stDate", frmDate)
.setTimestamp("edDate", enDate)
.list();
SimpleDateFormat sf=new SimpleDateFormat("dd-MM-YYYY");
String fromDate=null;
String toDate=null;
fromDate=sf.format(startDate);
toDate=sf.format(endDate);
sessionfactory.getCurrentSession().createQuery("from Customer where dateAdded BETWEEN '"+startDate+"' AND '"+endDate+"'");
SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Now use today date.
c.add(Calendar.DATE, 90);
Date fromDate = null, toDate = null;
String fromDateStr = formatter.format(new Date());
String toDateStr = formatter.format(c.getTime());
try {
fromDate = formatter.parse(fromDateStr);
toDate = formatter.parse(toDateStr);
} catch (ParseException e) {
e.printStackTrace();
}
query.setParameter("stDate", fromDate);
query.setParameter("edDate", toDate);
It's important to know that when using BETWEEN “setDate” will truncate the HQL date value passed as parameter and ignore the hours, minutes, seconds. This is very important to note especially if you have an HQL query checking between dates from different days because using “setDate” will interpret the date interval as between midnight of the specified dates.
The solution is to use “setParameter” instead of “setDate” which causes the HQL date values to be interpreted as dates and times.
here's a few examples in my site for those interested http://www.coding-dude.com/wp/java/hql-date-datetime-quick-tip/
I had similar issue. When we use end date (Wed Jan 29), the system looks for Wed Jan 29 00:00:00, which is just like choosing Jan 28. In order to avoid such case, we can add one day to the end date. This also explains why we do not have issue with the start date.
Surprisingly, this issue does not exist when we use hibernate criteria.
You need to annotate with #JsonFormat the same way the date filters and date field as follows:
Class Filter {
...
#JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd/MM/yyyy HH:mm", timezone="America/Sao_Paulo")
private Date startDate;
}
Class YourObject {
...
#JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd/MM/yyyy HH:mm", timezone="America/Sao_Paulo")
private Date DateAdded;
}
The pattern and timezone should be adjusted to your region.
Try something like this:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date fromDate = df.parse(startDate);
Date toDate = df.parse(endDate);
Criteria criteria = sessionfactory.getCurrentSession().createCriteria(Customer.class)
.add(Restrictions.between("dateAdded", fromDate , toDate ));
List<Customer> listCustomer = criteria.list();
Hope this helps..!!

Testing the Oracle to_date function

I'm writing an integration test in Grails using GORM.
I want to do something like the following:
delete from Statistic
where stat_date = TO_DATE(:month_year, 'MON-YYYY')
But I get the following error:
java.sql.SQLException: Unexpected token: TO_DATE in statement [delete
from statistics where stat_date=TO_DATE(?, 'MON-YYYY')]
I think the error is caused by the in memory database used by GORM (is it H2?) not supporting the to_date function.
Any ideas on how to write the delete SQL so that it works in a test and in live?
As I only really care about the Month and Year one thought I had would be to delete the records where the stat_date is between the first and last date of the given month.
Can any one think of a better way?
This still comes up as number 1 on google searches so here's what worked for me.
My unit tests/local environment build and populate a schema using sql files. I created the following alias in the sql file
-- TO_DATE
drop ALIAS if exists TO_DATE;
CREATE ALIAS TO_DATE as '
import java.text.*;
#CODE
java.util.Date toDate(String s, String dateFormat) throws Exception {
return new SimpleDateFormat(dateFormat).parse(s);
}
';
Notice the use of single quotes instead of $$ in h2 user defined functions as that is the only format that worked for me.
I had to adjust bluesman's answer in order to make it work for the date formats that are commonly used in our Oracle sql.
This version supports dateFormats like 'DD-MON-YYYY'
-- TO_DATE
drop ALIAS if exists TO_DATE;
CREATE ALIAS TO_DATE as '
import java.text.*;
#CODE
java.util.Date toDate(String s, String dateFormat) throws Exception {
if (dateFormat.contains("MON")) {
dateFormat = dateFormat.replace("MON", "MMM");
}
if (dateFormat.contains("Y")) {
dateFormat = dateFormat.replaceAll("Y", "y");
}
if (dateFormat.contains("D")) {
dateFormat = dateFormat.replaceAll("D", "d");
}
return new SimpleDateFormat(dateFormat).parse(s);
}
';
I found the tips on this blog post http://javatechniques.com/blog/dateformat-and-simpledateformat-examples/ helpful in figuring out how to translate the Oracle date formats into SimpleDateFormat's formats.
Yes, H2 doesn't support TO_DATE, it's in 1.4.x roadmap. Instead you can use the EXTRACT function that exists both in Oracle DB and H2.
java.util.Date toDate(String dateTime, String dateFormat) throws Exception {
if (dateFormat.contains("MON")) {
dateFormat = dateFormat.replace("MON", "MMM");
}
if (dateFormat.contains("Y")) {
dateFormat = dateFormat.replaceAll("Y", "y");
}
if (dateFormat.contains("D")) {
dateFormat = dateFormat.replaceAll("D", "d");
}
if (dateFormat.contains("HH")) {
dateFormat = dateFormat.replaceAll("HH", "hh");
}
if (dateFormat.contains("hh24")) {
dateFormat = dateFormat.replaceAll("hh24", "hh");
}
if (dateFormat.contains("MI") || dateFormat.contains("mi")) {
dateFormat = dateFormat.replaceAll("MI", "mi").replaceAll("mi", "mm");
}
if (dateFormat.contains("SS")) {
dateFormat = dateFormat.replaceAll("SS", "ss");
}
return new SimpleDateFormat(dateFormat).parse(dateTime);
}
Or you can define your own TO_DATE like
CREATE ALIAS TO_DATE AS $$
java.util.Date to_date(String value, String format) throws java.text.ParseException {
java.text.DateFormat dateFormat = new java.text.SimpleDateFormat(format);
return dateFormat.parse(value);
}
$$;
see http://www.h2database.com/html/features.html#user_defined_functions

blazeds converts BigDecimal to string

I have a Flex application that uses blazeds to connect to a Java backend. Using remoting, I give a call to an API to run a SELECT statement on a table (using conventional JDBC classes) in a Oracle database.
The table has 2 columns:
PRODUCT_CODE of type NVARCHAR2(32) and
DEMAND of type NUMBER(10, 0)
My Java API is as follows:
public List<?> getQueryResult(String query) {
Connection conn = DriverManager.getConnection(connStr, userName, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
ArrayList<?> result = new ArrayList<?>();
while(rs.next()) {
Object[] itemArray = new Object[2];
itemArray[0] = rs.getObject(1);
itemArray[1] = rs.getObject(2);
result.add(itemArray);
}
return result;
}
In my Flex side, I have a handler for result event of this remote operation:
private function onResult(e:ResultEvent) : void {
var result:ArrayCollection = (e.result as ArrayCollection);
}
Strangely, the values corresponding to DEMAND column are automatically converted to string (I debugged to find out that in backend, these were BigDecimal)
Any suggestions?
Yes indeed, the BigDecimal from Java is converted to String in ActionScript, as you can read in the developer guide. There is no BigDecimal in ActionScript so it was the only option - you cannot convert any BigDecimal to int or float.
If you are sure that your value represented as NUMBER(10,0) has values in the interval -2,147,483,648 - 2,147,483,647 you can convert it to an int in java - see the code below:
itemArray[1] = ((BigDecimal)rs.getObject(2)).intValue();

Resources