MS Access retrieve data between two dates using JDBC - java

I want to retrieve data between two dates from MS Access using JDBC.
I have tried
String query= "SELECT lastlogin FROM loginHistory " +
"WHERE lastlogin BETWEEN #01/07/2013# AND #03/07/2013#"+
"ORDER BY lastLogin DESC";
I am not getting the desired results.
Whats the problem. please help me out !
Thank You.

got the solution by transforming the date format from 01/07/2013 to 2013/07/01
String query= "SELECT lastlogin FROM loginHistory " +
"WHERE lastlogin BETWEEN #2013/07/01# AND #2013/07/03#"+
"ORDER BY lastLogin DESC";
Thank You all for supporting me..

Query missed the " in the end and you added in the middle.
Try
String query= "SELECT lastlogin FROM loginHistory " +
"WHERE lastlogin BETWEEN #01/07/2013# AND #03/07/2013# "+
"ORDER BY lastLogin DESC";

Your SQL syntax is correct, but you have an extra quotation mark in the middle of your code, directly after the first date in the BETWEEN clause.

I am not getting the desired results.
I believe then your code compiles but you are not getting the resultset what you expect. Although your code posted over here misses a quotation mark. I believe that it is a typo , or else the code wouldn't have compiled itself.
Check if the date string in the query is in correct format . Execute the query as a PreparedStatement :
String query= "SELECT lastlogin FROM loginHistory " +
"WHERE lastlogin BETWEEN ? AND ?"+
"ORDER BY lastLogin DESC";
And set the date strings after formatting it properly using Date format. Also check what is the datatype for your column , is it VARCHAR/String or DATE etc. You can even use the format() in the sql query itself :
Select lastlogin From loginHistory where format(lastlogin,"dd/mm/yyyy")
BETWEEN format(#01/07/2013#,"dd/mm/yyyy") AND
format(#03/07/2013#,"dd/mm/yyyy") ORDER BY lastLogin DESC;

Related

Order by JPQL Noob

I am trying to just to have my query ordered by my time stamp column and I cant figure out what is going wrong?
String sql = super._jpaql + "where entity.unit.ua=:ua order by timestamp desc";
Query query = super._entityManager.createQuery(sql).setParameter("ua", ua);
List<UnitNotesEntity> list = (List<UnitNotesEntity>) query.getResultList();
It should be:
where entity.unit.ua=:ua order by entity.timestamp desc

Query in Java - Subquery gone wrong or what?

I'm having a problem with this query of mine. I've spent almost an hour trying to correct it but still getting an error.
Heres my code:
sql = "INSERT INTO tbl_case \n" +
"(Case_ID, Employee_ID, Patient_ID, Chief_Complaint, Date) \n" +
"VALUES \n" +
"(\n" +
" '',\n" +
" 'EMP0001',\n" +
" '(SELECT Patient_ID from tbl_patient WHERE ID_no = '"+getPatient_ID()+"')',\n" +
" '"+txtcc.getText()+"',\n" +
" '"+time+"'\n" +
")";
dp.sop("Query 'Create Case': "+sql);
dp.Insertion(sql);
Note: dp stands for a class I inherited the methods from. dp.Selection is a simple executeQuery I made for retrieving data. dp.Insertion is for updating.
Here is the output of the query in String:
Query 'Create Case': INSERT INTO tbl_case
(Case_ID, Employee_ID, Patient_ID, Chief_Complaint, Date)
VALUES
(
'',
'EMP0001',
'(SELECT Patient_ID from tbl_patient WHERE ID_no = '10000201117')',
'Head Ache',
'2016-01-30 09:55:27'
)
and the error is a mysql syntax error near:
'10000201117)',
'Head Ache',
'2016-01-30 10:07:08'
)' at Line 7
anyone spotted whats wrong? I'm using mysql from xampp.
Since (SELECT Patient_ID from tbl_patient WHERE ID_no = '10000201117') is in single quotes you might want to try putting 10000201117 in double quotes.
For example:
'(SELECT Patient_ID from tbl_patient WHERE ID_no = "10000201117")'
I don't think you need to surround the SELECT statement with quotes.
As it is now, this part '(SELECT Patient_ID from tbl_patient WHERE ID_no = ' is interpreted as a value instead of part of a query.
Try: (SELECT ...) instead of '(SELECT ...)'

Relation "table name" doesn't exist postgresql

Hi I'm doing a query in java, i have java and posgres connected with the driver 9.3-1102-jdbc41
This is my query: query = "SELECT * FROM" +"\"users\" "+ " where user="+"'"+name+"'"+"and pass =" +"'"+pass+"'";
when I run it, this error appears:
Relation "users name" doesn't exist
Here and in others sites a possible solution is checking the quotes or the capital letters.
But I´m sure about the capital letters and this is what I tried:
query = "SELECT * FROM" +"\"users\" "+ " where user="+"'"+name+"'"+"and pass =" +"'"+pass+"'";
query = "SELECT * FROM users where user="+"'"+name+"'"+"and pass =" +"'"+pass+"'";
query = "SELECT * FROM" +"\"sysmar.users\" "+ " where user="+"'"+name+"'"+"and pass =" +"'"+pass+"'";
Error relation users does not exist
"SELECT * FROM users where user="+name+"and pass =" +pass;
syntax error near to pass
Thanks in advance for your answers and time
try:
"SELECT * FROM users where \"user\" ='"+name+"'and pass ='" +pass+"'";
But it's harmful for sql injection. See PreparedStatements.
For PostgreSQL you shouldn't need to put quotes around the table name unless it's a reserved keyword. Users isn't a keyword, but user just so happens to be one of them.
Your query is hard enough to read with the extra concatenation operations and spacing issues. Perhaps there is a syntax error and you just need to clean it up:
q = "SELECT * FROM users WHERE \"user\" = '" + name + "' AND pass = '" + pass + "'";
You want the final evaluated string to look like (for example):
SELECT * FROM users WHERE "user" = 'cory' AND pass = '12345';
But as others have mentioned, you should also switch to using prepared statements. This code is probably vulnerable to SQL injection attacks.
You really shouldn't concatenate variables with SQL queries, you are becoming vulnerable to SQL injection then. You better be using Prepared Statements which will allow you to write queries in more readable and secure fashion.
Connection conn = DriverManager.getConnection(...);
String queryString = "SELECT * FROM users WHERE user = ? AND pass = ?";
PreparedStatement query = conn.prepareStatement(queryString);
query.setString(1, name);
query.setString(2, password);
ResultSet result = query.executeQuery();

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.

Problem with PrepareStatement in Java

I have created table with 3 fields language,country,install type. When I write a query to print the maximum occuring value in each of the field, I am getting a weird problem.Can anyone say the reason.Here is my code.
PreparedStatement ps1= null;
ps1 = conn.prepareStatement("desc Configuration");
ResultSet rs1=ps1.executeQuery();
while(rs1.next()) {
System.out.print(rs1.getString(1)+":");
PreparedStatement ps2= null;
ps2 = conn.prepareStatement("select ? from Configuration c1 "+
" group by language "+
" having count(*) >= all " +
" ( select count(*) from Configuration c2 "+
" group by language )");
ps2.setString(1,rs1.getString(1));
ResultSet rs2=ps2.executeQuery();
while(rs2.next())
System.out.print(rs2.getString(1));
System.out.println();
}
The output I am getting here is language:language But the output what I am expecting is
language:english like that. I am getting later output if i replace '?' with language in the prepare statement.But if i give the same with ? I am getting what ever I have given for ps2.setString.
Why is this happening. Any solutions?
? in prepared statements is not a placeholder for textual substitution, it's a parameter, therefore its value is always interpreted as data, not as an arbitrary part of query syntax.
So, in this case the actual query being executed is an equivalent of select 'language' from ....
If you need to substitute parts of the query other than data, you have to use concatenation (beware of SQL injections!):
ps2 = conn.prepareStatement("select "
+ rs1.getString(1)
+ " from Configuration c1 group by language having count(*) >= all( select count(*)from Configuration c2 group by language )");
You can't set column names using a PreparedStatement. You can only set column values.
Instead of using this approach, you will have to build the sql yourself using concatenation, for example:
String sql = "select "+ rs1.getString(1) + " from Configuration c1 group by language having count(*) >= all( select count(*)from Configuration c2 group by language)";
The '?' mark in ps2 is recognized as literal-string. Not as a column name.

Categories