I did a SQL query in Java as follows:
"SELECT A.ID_MACHINE, A.HEURODATAGE, A.COMPTEUR, B.LIBELLE_IDMACHINE, C.LIBELLE_STATUT, C.CODE_COULEUR FROM ROXJAVA.MACH0004 A " +
"JOIN ROXJAVA.MACH0003 B ON A.ID_MACHINE = B.ID_MACHINE " +
"JOIN ROXJAVA.MACH0002 C ON B.CODE_MACHINE = C.CODE_MACHINE " +
"WHERE A.ID_MACHINE = ? AND A.HEURODATAGE BETWEEN '?' AND '?' AND A.CODE_STATUT = C.CODE_STATUT AND C.CODE_COULEUR = ? " +
"ORDER BY A.HEURODATAGE DESC";
In my WHERE it finds "Heurodatage" which must contain a time and a date with this format:
'2018-07-03 09:30:00.000'
I then want to retrieve the results of this query with the help of a method that takes into account the different attributes that I need to replace the? in my request.
But now I can not determine the type of my dates.
I'm getting "type not match" when I try to run with a String.
If the column is a date column, you want to pass in a date type:
PreparedStatement ps = ...;
ps.setDate(N, java.sql.Date.valueOf(your_date_value));
where it would be best if your_date_value is a java.time.LocalDate, but could also be parsed from a String (in a valid format).
Related
It is necessary to select dataset using JPQL query with optional condition - comparing the field value (LocalDateTime type) with a user-specified parameter (also LocalDateTime type).
First I made a well working code:
return entityManager.createQuery(
"SELECT new com.******.*******.*******.****.models.dto.SomeDto " +
"(s.id, " +
"s.userId) " +
"s.persistDate) " +
"FROM Some s WHERE s.userId = :userId
AND s.persistDate >= :userDateTime", SomeDTO.class)
.setParameter("userId", userId)
.setParameter("userDateTime", userDateTime)
This code works but there is one problem:
this condition may exist or may not exist - dependent on app logic. Therefore, there is a need not to use injection using .setParameter (for this condition), but to form a string (which may be empty) depending on the logic and then add to the request:
String extraCondition = (userDateString.equals("false")) ? "" :
"AND s.persistDateTime >= " + userDateString;
return entityManager.createQuery(
"SELECT new com.******.*******.*******.****.models.dto.SomeDto " +
"(s.id, " +
"s.userId) " +
"s.persistDate) " +
"FROM Some s WHERE s.userId = :userId " + extraCondition, SomeDTO.class)
.setParameter("userId", userId)
But the problem is that no matter how I tried to format the userDateString variable, I get an Internal Server Error.I even tried using just a text string instead of variable (tried with different formatting):
String extraCondition = (userDateString.equals("false")) ? "" :
"AND s.persistDateTime >= 2023-01-27T23:30:50";
But the result is also bad - Internal Server Error.
I also tried using the .isAfter method instead of the ">=" operator, but that didn't help either.
How to inject LocalDateTime values comparing into query as String?
even if the date string may or may not be necesssary, you can (and should!) still use parameter injection, not formatted values.
Basically, your code should look like this:
String queryStr = ....;
boolean someCondition = <expensive_test_here>;
if(someCondition) {
queryStr += " AND s.persistDate >= :userDateTime";
}
Query q = em.createQuery(queryStr).setParameter("userId", userId);
if(someCondition) {
q.setParameter("userDateTime", userDateTime);
}
i have a table "queue_in_progress" whose structure is like the following :
I want to update the DATE_TIME_TOKEN_TAKEN , CE_PK , Service_status of the table . For this , I have the following code :
String sqlQuery = "UPDATE queue_in_progress\n" +
"SET CE_PK="+ce_pk+" ,SERVICE_STATUS=1 \n" +
"WHERE CATEGORY_PK="+Category_PK+" AND TOKEN_NO="+ Token_PK+" "
+ " AND SERVICE_COUNTER="+service_counter+" AND SERVICE_CENTER_PK="+service_center+" ;";
java.util.Date utilDate = new Date(); // Convert it to java.sql.Date
java.sql.Date date = new java.sql.Date(utilDate.getTime());
PreparedStatement stmt = con.prepareStatement(sqlQuery);
stmt.setDate(1, date);
success = stmt.executeUpdate();
But the success flag is returning -1 and the table is not updated . What is the problem ? What can I do to fix this problem ?
I don't see DATE_TIME_TOKEN_TAKEN=? in your query (the bind parameter), I think you wanted
String sqlQuery = "UPDATE queue_in_progress SET DATE_TIME_TOKEN_TAKEN=?, "
+ "CE_PK=" + ce_pk
+ ", SERVICE_STATUS=1 WHERE CATEGORY_PK="
+ Category_PK
+ " AND TOKEN_NO="
+ Token_PK
+ " AND SERVICE_COUNTER="
+ service_counter + " AND SERVICE_CENTER_PK=" + service_center;
OR if you want DATE_TIME_TOKEN_TAKEN to ALWAYS hold Current Time value, you can Set it on your Database side, no need to set it in your code.
ALTER TABLE queue_in_progress
MODIFY DATE_TIME_TOKEN_TAKEN DEFAULT CURRENT_TIMESTAMP;
I would like to parse an input date in java, and then use it in a query as a condition in a select in oracle database.
String date = "2013.11.05";
Date checkDate = new SimpleDateFormat("yyyy.MM.dd").parse(date);
String qString =
"SELECT DISTINCT T " +
"FROM T5PFArfolyamArch T " +
"WHERE T.arfTipus = :vcRateKod AND T.arfErvkezd = :checkDate AND T.araValid IN ('I','M')";
Query query = entityManager.createQuery(qString);
query.setParameter("vcRateKod", tipus);
query.setParameter("checkDate", checkDate);
But it gives 0 result, like the date is not equal or right format to select anything.
try this
query.setParameter("checkDate", checkDate, TemporalType.DATE);
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 need to write a query to get an object between a range of time, currently the query looks like this:
Timestamp from = ...
Timestamp to = ...
getHibernateTemplate().find("from " + Person.class.getName() + " ml where ml.lastModifiedOn>="+from.toString()+" and m1.lastModifiedOn<=" + to.toString());
However, this doesnot work for obvious reasons. How can I format the timestamp to be acceptable by the query.
org.springframework.orm.hibernate3.HibernateQueryException: unexpected token: 16 near line 1, column 123 [from Person ml where ml.lastModifiedOn>=2010-02-12 16:00:21.292 and m1.lastModifiedOn
You're missing single quotes in your current query. The following should work:
from Person ml where ml.lastModifiedOn
between '2010-02-12 16:00:21.292' and '2010-02-12 23:00:21.292'
Note that I don't know why you're not passing Date instances to the following query:
from Person ml where ml.lastModifiedOn between :from and :to
Are you using java.sql.Timestamp here? If yes, you shouldn't.
You can simply pass a long (from.getTime()) in the comparison, if it is represented as long in the DB.
Otherwise you can use these functiomns: second(...), minute(...), hour(...), day(...), month(...), and year(...)
How about something like this?
String sql = "from " + Person.class.getName() + " ml where ml.lastModifiedOn>= ? and m1.lastModifiedOn<= ?";
Date from = ...;
Date to = ...;
getHibernateTemplate().find(sql, new Object[] {from,to});
If you want to query for something between you can do the following:
public List findPerson() {
Date from = ...;
Date to = ...;
return entityManager.createQuery(
"SELECT p from Person p WHERE p.lastModifiedOn BETWEEN ?1 AND ?2")
.setParameter(1,from, TemporalType.DATE)
.setParameter(2,to, TemporalType.DATE).getResultList();
}
You might need to change TemporalType.DATE to whatever you are using