I'm trying to set a sql query like this:
SELECT id
FROM example_table
WHERE agent not like '%example'
I tried that in SQL Developer and works fine, but in Java I don`t get what I want to:
String= "%example"
(...)
query=""
+ "SELECT id"
+ "FROM example_table"
+ "WHERE agent not like ?"
(...)
pst.setString(n++, String);
(...)
I don't get any error but the query doesn't give the result I want, I think the point is that setting the String is not compatible with "%".
Thank you in advance
EDIT:
SOLUTION:
String= "example"
(...)
query=""
+ "SELECT id"
+ "FROM example_table"
+ "WHERE agent not like **concat('%', ?)"**
(...)
pst.setString(n++, String);
(...)
That simple :)
Related
I have this application, java spring boot and mysql db.
When i try to run the following query, i get this error.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'email ='rahul#gmail.com.com'' at line 1
Does anyone know know why?
#Query(value = "SELECT voucher_code FROM voucher INNER JOIN "
+ "offer ON offer.name = voucher.offer "
+ " email =:email", nativeQuery = true)
List<Voucher> getVouchers(#Param("email") String email);
You are missing something between the two conditions offer.name = voucher.offer and email =:email, probably a WHERE, perhaps an AND/OR. I guess you wanted this:
#Query(value = "SELECT voucher_code FROM voucher INNER JOIN "
+ "offer ON offer.name = voucher.offer "
+ "WHERE email =:email", nativeQuery = true)
List<Voucher> getVouchers(#Param("email") String email);
I have been defeated by the great SQL boss and am now requesting assistance.
Ive removed spaces in table names to avoid confusion
Anyways, I have two tables Orders and Order Details. I need to query a few columns from both. So far, I can query Orders just fine, but when it comes to querying Order Details, or the two together, I get errors.
My Question is this: How do I query two tables?
(note: semicolon is at the bottom, imagine it's there)
Here's what works so far on Orders:
String queryString = "select `Order Date`, Freight "
+ "from Orders "
+ "where Orders.`Order ID` = ? "
Here's my attempt to just grab one column from Order Details and the error to follow
String queryString = "select Product "
+ "from `Order Details` "
+ "where `Order Details`.`Order ID` = ? "
net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.1 user lacks privilege or object not found: ORDER DETAILS.ORDER ID
at net.ucanaccess.jdbc.UcanaccessConnection.prepareStatement(UcanaccessConnection.java:528)
Here's my attempt to grab both at once and the error to follow
String queryString = "select `Order Date`, Freight, Product "
+ "from Orders, `Order Details` "
+ "where Orders.`Order ID` = ? "
net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.1 user lacks privilege or object not found: PRODUCT
at net.ucanaccess.jdbc.UcanaccessConnection.prepareStatement(UcanaccessConnection.java:528)
Here's the above attempt with an extra line at the bottom combining them (I don't know what this does), but it alters the error.
String queryString = "select `Order Date`, Freight, Product "
+ "from Orders, `Order Details` "
+ "where Orders.`Order ID` = ? "
+ "and Orders.`Order ID` = `Order Details`.`Order ID`"
net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.1 user lacks privilege or object not found: ORDER DETAILS.ORDER ID
at net.ucanaccess.jdbc.UcanaccessConnection.prepareStatement(UcanaccessConnection.java:528)
Putting the table name in quotes doesn't work in any SQL-Server i know without changing some configuration.
The correct way is using []:
MSSQL-Example:
SELECT * FROM [Order Details]
Your query may look like this:
String queryString = "SELECT Product "
+ "FROM [Order Details] "
+ "WHERE `Order ID` = ? "
But i would suggest to work without whitspaces within any identifier.
Read about JOIN statements, this will allow you to work with two tables. Try use something like “SELECT your_columns FROM orders o JOIN orderDetails od ON o.id = od.order_id”.
Errors like “object not found” means you didn’t create table. Wish it’ll help.
Edit-
I'll add the use case to clear up the function of this.
The user will select two dates - a start date and an end date - these are then passed on and used to select the tables (each year has its own table). In one use case where the two given dates lie in the same year it's a simple query on that table alone.
However, if the two dates are different years I will need to join all tables (so 2011-2013 will be three tables connected, to search through) and thus, I want a dynamic fix to this. I know building up a query like below is against security - just thought something similar would work. As the system will get new tables each year I also dont want to have to manually add however many new queries for each case (2011-2016, 2014-2018, 2011-2019.. etc)
I have a question about whether it is possible to create a dynamic query as a String like below and then pass that through to service -> repository, and use that as a query?
for (int i = 0; i < yearCondition; i++) {
if (i == 0) {
query += "SELECT md.Device_ID, l.locationRef, " + reportRunForm.getStartDate() + " as 'From Date', "
+ reportRunForm.getEndDate() + " as 'To Date' "
+ "from mData.meterdata" + iDateStart.substring(0, 4)
+ " join MOL2.meters m on device_ID = m.meterUI "
+ "join MOL2.locations l on m.locationID = l.locationID "
+ "join MOL2.meterreg mr on m.meterID = mr.meterID "
+ "where mr.userID = ?1";
}
query += "UNION SELECT md.Device_ID, l.locationRef, " + reportRunForm.getStartDate() + " as 'From Date', "
+ reportRunForm.getEndDate() + " as 'To Date' "
+ "from mData.meterdata" + (Integer.parseInt(iDateStart.substring(0, 4))+i)
+ " join MOL2.meters m on device_ID = m.meterUI "
+ "join MOL2.locations l on m.locationID = l.locationID "
+ "join MOL2.meterreg mr on m.meterID = mr.meterID "
+ "where mr.userID = ?1";
}
I may have the wrong idea with how this works, and I know I could create and persist a query through entitymanager, but wanted to know whether doing it through the repository would be possible?
My thought was I'd build up the query like above, pass it through to service and then to repository, and bind it as value in #Query annotation but this doesn't seem possible. I'm likely approaching this wrong so any advice would be appreciated.
Thanks.
Edit -
Had a goof. Understand doing it at all like that is stupid, an approach to build up something similar is what I'm looking for that is still secure.
Maybe this annotations before your POJO can help
#org.hibernate.annotations.Entity(dynamicInsert = true)
for example two tables district and constituency ...
Dynamic query
query += "select *from constituency c where 1=1";
if(constituencyNumber!=null)
query +=" and c.constituency_number like '"+constituencyNumber+"%'";
query += " group by c.district_id";
OR
select *from constituency c where (c.constituency_number is null or c.constituency_number like '1%') group by c.district_id;
I am facing a problem usign JPA, and more specifically using a IN clause.
The best way is, I think, to show you my code :
#NamedQuery(name = "Commande.findCustom", query = "SELECT DISTINCT [myFields] "
+ "FROM Commande c WHERE "
+ "[SomeCriterias] AND "
+ "c.ID IN (SELECT t.ID FROM SubTable t "
+ "WHERE t.IDX IN :param) AND [otherCriterias]"),
I then get an error from MySQL :
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.ID FROM SubTable t1 WHERE (t1.IDX IN (168)'
I am looking for a response but can't find anything ...
I tied to delete a IN clause, the problem is still the same (so it's not a double IN use problem)
my :param is a List of objects, that i got by using the Object.find() method. As you can see, it returns the ID (168). But I can't seem to find the problem ...
Any help would be greatly appreciated, thank you
EDIT : Full query
#NamedQuery(name = "Commande.findCustom", query = "SELECT DISTINCT c.idChargement, c.libelle, "
+ "c.codeTransporteur, c.reference, c.dateCreation, c.dateChargementPrevu, "
+ "c.dateValidationChargement, c.dateLivraisonPrevue, c.codeDestinataire, "
+ "c.raisonSocialeDestinataire, c.adresseDestinataire, c.codePostalDestinataire, "
+ "c.villeDestinataire, c.paysDestinataire, c.contactDestinataire, "
+ "c.telephoneDestinataire, c.mailDestinataire, c.poidsCommande, c.nombreColis, "
+ "c.nombreUniteManutention, c.typeUniteManutention, c.prendreRDV, c.commentaires "
+ "FROM Commande c WHERE "
+ "c.idChargement = :idChargement AND c.codeTransporteur = :codeTransporteur AND "
+ "(c.dateCreation BETWEEN :dateDebut AND :dateFin) AND "
+ "c.idDernierStatut IN (SELECT l.idListeStatutsCommande FROM Listestatutscommande l "
+ "WHERE l.idStatut IN :idStatut) AND c.raisonSocialeDestinataire = :raisonSociale AND "
+ "c.adresseDestinataire = :adresseDestinataire AND c.codeDestinataire = :codeDestinataire "
+ "AND c.codePostalDestinataire = :codePostal AND c.villeDestinataire = :villeDestinataire "
+ "AND c.paysDestinataire = :codePays")
And the Error Message
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.idListeStatutsCommande FROM listestatutscommande t1 WHERE (t1.IdStatut IN (168)'
As you are getting error from MYSQL not Hibernate, you could try to find out what query actually is generated. To do this, use proxy invoker like p6spy and then everything should be clear. Check p6spy site. When you do, try to invoke such generated SQL yourself and try to fix it. I used such method when I had some troubles using JPA's joins fetches and stuff. Very helpfull in diagnosing such problems.
Ok so I found the problem, and then the answer. Thanks #Antoniossss, the fact is that I was looking at the wrong part of the query.
The error was here : c.idDernierStatut IN ...
The fact is that this part is a foreign key. And when you want to search on it, you have to consider it as an object. So the correct form is c.idDernierStatut.idListeStatutsCommande IN to get the ID.
Thank you to both of you for your time anyway !
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();