How to search between two dates in java with Sqlite database - java

I am using jCalender to input date
String from_date = ((JTextField) txt_bilty_date_start.getDateEditor().getUiComponent()).getText();
String to_date = ((JTextField) txt_bilty_date_end.getDateEditor().getUiComponent()).getText();
String sql = " "; //what query I need to use

I'm not java pro but SQL statement could be like this
select * from POSTS where Id = 1
and Date between '2011/02/25' and '2011/02/27'
or can use
select * from POSTS where Id = 1
and Date >= '2011/02/25' and Date <= '2011/02/27'

Related

Not a Valid Month in Hibernate

Hi im trying to get number of rows from table using Hibernate based on start and end Date but im Getting not a Valid Month error
Session session = sessionFactory.getCurrentSession();
startDate = "13-02-02 00:00:00";
endDate = "17-02-02 00:00:00";
try{
String hql = "select Count(*) from mytable where PERIOD_START_DATETIME between '"
+ startDate + "' AND '" + endDate + "'";
Query query = session.createQuery(hql);
long count=(long) query.uniqueResult();
return count;
} finally{
session.close();
}
This is my table description
Name NULL TYPE
NAME NOT NULL VARCHAR2(255 CHAR)
PERIOD_END_DATETIME NOT NULL TIMESTAMP(6)
PERIOD_START_DATETIME NOT NULL TIMESTAMP(6)
PROD_OFFER_TERM_TYPE_ID NOT NULL NUMBER(19)
Using string concatenation for generating SQL queries is usually a bad idea because
it's bad for performance (causes re-parsing of the SQL statement for every execution)
it's prone to SQL injection attacks
HQL supports bind variables / prepared statements, so this should work:
String hql = "select Count(*) from mytable where PERIOD_START_DATETIME between :startdate AND :enddate ";
Query query = session.createQuery(hql);
query.setParameter("startdate", startDate);
query.setParameter("enddate", endDate);
(where startDate and endDate are actual java.sql.Timestamp values, not strings).
As the start/end times are SQL TIMESTAMPs in the DB, you can pass in a Timestamp object into the query as follows:
Session session = sessionFactory.getCurrentSession();
final DateFormat df = new SimpleDateFormat("yy-MM-dd");
// omitting the time part will set the time to midnight (00:00:00)
Timestamp start = new Timestamp(df.parse("13-02-02").getTime());
Timestamp end = new Timestamp(df.parse("17-02-02").getTime());
try {
String hql =
"select Count(*) from mytable where PERIOD_START_DATETIME between ? AND ?";
Query query = session.createQuery(hql)
.setTimestamp(0, start)
.setTimestamp(1, end);
long count = (long) query.uniqueResult();
return count;
} finally {
session.close();
}
Make sure you actually pass date values in your query.
You can use the to_date function where you specify the format of the date, as it is represented in the string.
select Count(*)
from mytable
where PERIOD_START_DATETIME between to_date(startDate,'DD-MM-YYYY HH24:MI:SS') AND to_date(endDate,'DD-MM-YYYY HH24:MI:SS');
select Count(*)
from mytable
where PERIOD_START_DATETIME between TO_TIMESTAMP(:startDate, 'YY-MM-DD HH24:MI:SS') AND TO_TIMESTAMP(:endDate, 'YY-MM-DD HH24:MI:SS')

How to Insert date from JFormatedTextField with mask

I am working on a app there are some JFormatedTextFields with mask formatted (##/##/#### as dd/MM/YYYY). I am trying to insert these date into Database but it is showing an error "Error Converting data type nvarchar to Date"
Error Converting data type nvarchar to Date
but I could not find any problem in my sql procedure because if I run that procedure using sql query analyzer it is working but if I try to execute from app it is showing error
here is my all codes
sql procedure
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Proc_set_ExamDeclaration]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Proc_set_ExamDeclaration]
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE Procedure [dbo].[Proc_set_ExamDeclaration]
(
#SchoolCode nvarchar (10),
#ClassCode nvarchar (4),
#GroupName nvarchar(50),
#ExamCode nvarchar (4),
#RegistationFess numeric(38,2),
#RegistatinStartDate date,
#RegistatinEndDate date,
#ExamStartDate date,
#ExamStatus nvarchar(10)
)
as
BEGIN
-- Insert statements for procedure here
Declare #RFirst as Date, #REnd as Date, #EStart as Date
set #RFirst = CONVERT(varchar, #RegistatinStartDate, 103)
set #REnd = CONVERT(varchar, #RegistatinEndDate, 103)
set #EStart = CONVERT(varchar, #ExamStartDate, 103)
IF NOT EXISTS (SELECT * FROM [dbo].[ExamDeclaration] where ClassCode = #ClassCode AND GroupName = #GroupName AND ExamCode = #ExamCode AND ExamStatus = 'Active')
BEGIN
INSERT INTO ExamDeclaration (SchoolCode, ClassCode,GroupName,ExamCode,RegistationFess,RegistatinStartDate,RegistatinEndDate,ExamStartDate,ExamStatus)
VALUES (#SchoolCode, #ClassCode,#GroupName,#ExamCode,#RegistationFess,#RFirst,#REnd,#EStart,#ExamStatus)
END
ELSE
Update ExamDeclaration
set RegistationFess = #RegistationFess,
RegistatinStartDate = #RFirst,
RegistatinEndDate = #REnd,
ExamStartDate = #EStart,
ExamStatus = #ExamStatus
Where ClassCode = #ClassCode AND GroupName=#GroupName AND ExamCode = #ExamCode
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
and here is the java codes
String School_Code = txt_SchoolCode.getText();
String ClassCode = txt_ClassCode.getText();
String groupName = com_groupname.getSelectedItem().toString();
String examCode = txt_ExamCode.getText();
String fees = txt_fees.getText();
String RStart = txt_RStart.getText();//((JTextField) txt_RStart.getDateEditor().getUiComponent()).getText();
String REnd = txt_REnd.getText();//((JTextField) txt_REnd.getDateEditor().getUiComponent()).getText();
String EStart = txt_ExamStart.getText();//((JTextField) txt_ExamStart.getDateEditor().getUiComponent()).getText();
String Estatus = com_eStatus.getSelectedItem().toString();
if(ClassCode.isEmpty() && examCode.isEmpty() && fees.isEmpty() /*&& RStart.isEmpty() && REnd.isEmpty() && EStart.isEmpty()*/){JOptionPane.showMessageDialog(null, "All Fields are Required !!");}
else{
try{
String sqlExamD = "Exec Proc_set_ExamDeclaration ?,?,?,?,?,?,?,?,?";
pst=conn.prepareStatement(sqlExamD);
pst.setString(1, School_Code);
pst.setString(2, ClassCode);
pst.setString(3, groupName);
pst.setString(4, examCode);
pst.setString(5, fees);
pst.setString(6, RStart);
pst.setString(7, REnd);
pst.setString(8, EStart);
pst.setString(9, Estatus);
pst.execute();
JOptionPane.showMessageDialog(null, "Saved Successfuly");
btn_new.doClick();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
any Idea where is the problem in my codes?
I am using java netbeans and sql server 2008
Thank you.
It looks to me that you have you assign your date variables in Java as strings, but you have them actually defined as dates:
String RStart = txt_RStart.getText();
...
#RegistatinStartDate date
And then you try to convert from date to varchar but assign it back to a date?
Declare #RFirst as Date
...
set #RFirst = CONVERT(varchar, #RegistatinStartDate, 103)

Java Statement executeQuery returns different results than in SQLDeveloper when the same query is run

I'm trying to retrieve results from a Oracle 11.2.0.3 database like in the example given at http://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.html
String query = createQuery(); // SQL query to be used
System.out.println(query);
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
System.out.println("output of first 10 results");
while(rs.next()){
if (i < 10){
String val1= rs.getString(1);
String val2 = rs.getString(8);
String val3 = rs.getString(13);
System.out.println("val1: " + val1 +
", val2: " + val2 + ", val3: " + val3);
}
i++;
}
However, some of the rows returned are different from when I run the same query in SQLDeveloper connected to the same DB schema.
Actually, some of the rows returned in the ResultSet do not match my query.
I am logging into the DB with the same user for both. The java application is using the ojdbc.jar provided at http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-112010-090769.html for the Oracle Database 11g Release 2 (11.2.0.3) JDBC Drivers
What could cause such a scenario to happen? There are no changes being made to the tables involved.
The sanitized query:
SELECT DISTINCT T1.COL1, T1.COL2, T1.COL3, T1.COL4, T1.COL5, T1.COL6, T1.COL7, T1.COL8, T1.COL9, COL10, T1.COL11, T1.COL12, T1.COL13
FROM VIEW1 T1, VIEW2 T2
WHERE T1.COL1 = T2.COL1
AND ( (NLSSORT(T1.COL8, 'NLS_SORT=BINARY_AI')=NLSSORT(TO_DATE('2014-05-12 15:25:02', 'YYYY-MM-DD HH24:MI:SS'), 'NLS_SORT=BINARY_AI')
AND T1.COL13<'Example')
OR (NLSSORT(T1.COL8, 'NLS_SORT=BINARY_AI')<NLSSORT(TO_DATE('2014-05-12 15:25:02', 'YYYY-MM-DD HH24:MI:SS'), 'NLS_SORT=BINARY_AI')) )
AND ( T2.ANOTHERCOL = 'SOMEVALUE' AND T1.COL1 = T2.COL)
ORDER BY NLSSORT(COL8, 'NLS_SORT=BINARY_AI') DESC, COL8 DESC, T1.COL13 DESC
In the output, I get:
val1: anid, val2: 2014-05-12 15:29:39, val3: doesnotmatter
As far as I'm aware, that row should not be returned since 2014-05-12 15:29:39 is not less than 2014-05-12 15:25:02. And indeed that row is not found when I run the query in SQLDeveloper.
I guess that col8 is of type date, and I think you problem is in
(NLSSORT(T1.COL8, 'NLS_SORT=BINARY_AI')=NLSSORT(TO_DATE('2014-05-12 15:25:02', 'YYYY-MM-DD HH24:MI:SS'), 'NLS_SORT=BINARY_AI')
your actions:
convert '2014...' to date
convert result to string
convert col8 to string using default format for date column
if your SQL Developer and your java client have different default format for date - you will get different result
I would recomend to change that line to
T1.COL8 = TO_DATE('2014-05-12 15:25:02', 'YYYY-MM-DD HH24:MI:SS')
Also, you don't need NLSSORT in WHERE clause, there is no sorting there.
Now I am thinking that I am wrong.. just don't want to delete it all :)
second try...
one date is 31322D6D61792D313400
another one is 31322D6D61792D313400
they are no less that the other
Query to check
select
NLSSORT(TO_DATE('2014-05-12 15:25:02',
'YYYY-MM-DD HH24:MI:SS'), 'NLS_SORT=BINARY_AI'),
NLSSORT(TO_DATE('2014-05-12 15:29:39',
'YYYY-MM-DD HH24:MI:SS'), 'NLS_SORT=BINARY_AI')
from dual
Any differences if instead of function, modify session?:
ALTER SESSION SET NLS_COMP = 'LINGUISTIC';
ALTER SESSION SET NLS_SORT = 'BINARY_AI';

JPA query equivalent to mysql query

Below is mysql query which is working fine and giving me expected results on mysql console.
select * from omni_main as t where t.date_time BETWEEN STR_TO_DATE(CONCAT('2011', '08', '01'),'%Y%m%d') AND LAST_DAY(STR_TO_DATE(CONCAT('2012', '08','01'), '%Y%m%d')) group by year(date_time),month(date_time)
I need its JPA equivalent query. Below is what I am trying but its returning nothing.
String queryStr = "select * from OmniMainEntity o where o.dateTime BETWEEN STR_TO_DATE(CONCAT('"+fromYear+"', '"+fromMonth+"','01'), '%Y%m%d') AND "
+"LAST_DAY(STR_TO_DATE(CONCAT('"+toYear+"', '"+toMonth+"','01'), '%Y%m%d'))";
Query query = manager.createQuery(queryStr);
System.out.println("Result Size: "+query.getResultList().size());
Here fromYear, fromMonth, toYear, toMonth are method parameters using in creating queryStr.
Please suggest where I may wrong!
Any other way to achieve goal is also welcome!
As you are using JPA Query, it would be better to not use database-specified sql function, such as STR_TO_DATE.
You can have a try by this way.(A Hibernate way, JPA should be similiar):
First, you can parse a java.util.Date object from "fromYear" and "fromMonth" like below:
DateFormat df = new SimpleDateFormat("yyyyMMdd");
Date startDate = df.parse(fromYear + "" + fromMonth + "01");
Date endDate = df.parse(.....);
Then, set them into the JPA query.
String queryStr = "select * from OmniMainEntity o where o.dateTime BETWEEN :startDate AND :endDate)"; // The query now changed to database independent
Query query = manager.createQuery(queryStr);
query.setDate("startDate", startDate);
query.setDate("endDate", endDate);
At last, doing the search:
System.out.println("Result Size: "+query.getResultList().size());
Your query doesn't have a verb in it. You probably want SELECT in there:
SELECT o FROM OmniMainEntity o WHERE...
Also, you should be using parameterized and typed queries, and it's usual to use short names (o instead of omniMainEnt) to make your queries readable.

How can i search for the year in a date via a query?

The records in the db look like this:
10//12/2013
10/13/2013
10/16/2013
10/20/2013
I want to search 2013 in the above records. Do i have to split first above values?
from CustomerRelations where DATE like'" + input + "'
Can I use like here?
Or how else can I do this?
Query q = session.createQuery("from CustomerPayment where DATE like '" + code + "'");
The Above code does not work.
Since you've saved the dates as VARCHAR do a wildcard String match
Query q = session.createQuery("from CustomerPayment where DATE like '%" + code + "'");
LIKE clause lets you use two wilcards:
_ = matches just one single character
% = matches any number of characters
Ideally, you should have created your table with a TIMESTAMP column. That would allow you to compare dates accurately and build queries like "fetch all customer payments in the last three months" etc.
you can use
datepart(year,datefield)
where datefield is your field from which you want to retrieve the year
Query q = session.createQuery("SELECT date FROM CustomerPayment WHERE datepart(year,"+Convert.ToDateTime(datefield)+")="+ input+";
Try changing your query to
Query q = session.createQuery("SELECT date FROM CustomerPayment WHERE date LIKE '%"+input+"'"
since your date field is a string, you must do the lookup via a string compare

Categories