Update syntax error - java

Is it possible to insert a from field in a update query?
i need it because before update something,i need to do some controls.
p.s i know that i have to use prepared statement but i want to know this error,i suppose it is a missing quote,that i can't see.
the error: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'from warehouse,product where warehouse.idProduct=shop.idProduct and warehouse.id' at line 1
int rs = st.executeUpdate("UPDATE shop SET quantity='"
+ Quantity
+ "' from warehouse,product where
warehouse.idProduct=shop.idProduct and
warehouse.idProduct=product.id and product.brand='"
+ Brand + "' and product.productType='" + Product
+ "'");

That just isn't valid SQL. UPDATE statements cannot have a FROM clause.
Single-table syntax:
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
Multiple-table syntax:
UPDATE [LOW_PRIORITY] [IGNORE] table_references
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]

I think you want an update with a join:
UPDATE shop s join
warehouse w
on w.idProduct = s.idProduct join
product p
on w.idProduct = p.id and
p.productType = '"+Product+"' and
p.brand = '" + Brand + "'
SET s.quantity = "+ Quantity
As a note. I'm guess that Quantity is numeric. If so, you don't need quotes around the value.

Related

MySQL query not working in Java

String sqlInsertBeacon = "INSERT INTO `beacon` (zone_id, location) VALUE ('(SELECT id FROM zone WHERE GeographicalID = '" + geometry3 + "')', Point(" + x_coordinate + "," + y_coordinate + "))";
System.out.println("The SQL query is: " + sqlInsertBeacon); // Echo for debugging
int countInserted3 = stmt.executeUpdate(sqlInsertBeacon);
System.out.println(countInserted3 + " records inserted.\n");
When I run the above code, the build is successful but the program stops when it reaches the execute line. I am entering using this sql query to insert data into a mysql database. I am not sure where the error is in my query? Can anyone suggest an alternative way or find the mistake?
The output of the program is this, as you can see the program, stops running after the second line:
The SQL query is: INSERT INTO table
(zone_id, location)
VALUES
((SELECT id FROM zone WHERE GeographicalID = '6311599'), Point(-121.9453802,37.3256131) )
;
BUILD SUCCESSFUL (total time: 6 seconds)
For additional information incase it helps:
The stmt, is created like this:
try (
// Step 1: Allocate a database 'Connection' object
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/adhwere2?useSSL=false", "root", "your_new_password"); // MySQL
// Step 2: Allocate a 'Statement' object in the Connection
Statement stmt = conn.createStatement();) {
and the catch exception is :
} catch (SQLException ex) {
}
Try something like this:
String sqlInsertBeacon = "INSERT INTO `beacon` (zone_id, location)" +
" VALUES ( (SELECT id FROM zone WHERE GeographicalID = '" + geometry3 + "'), Point(" +
x_coordinate + "," + y_coordinate + "))";
Just removed the apostrophes aroung the inner SELECT and replaced VALUE with VALUES...
The problem was because the sub-query was returning more than one result, and printing out a stack trace helped debug this error. Using Limit 1 in the sub query also solved this issue.
please use query according to this syntax:
INSERT INTO table
(column1, column2, ... )
VALUES
(expression1, expression2, ... ),
(expression1, expression2, ... ),
...;
your table name is in single quotes and its VALUES not value mind these small things
Correct INSERT INTO SELECT statement looks like this:
INSERT INTO table2
SELECT * FROM table1
WHERE condition;
And you can use PreparedStatement to set parameters in your query.

What is wrong with this QUERY, why it is giving me following error?

I'm learning swing in java. I've make a jtable that is populated by database's values (sql table --> user(id, name, age)). I want to make jtable that is if i change values from jtable is should also update database on click on button. but where i query is executed an error occurs. I want to know what is issue with this query ???
QUERY:
String sql = "UPDATE \'alarm bell marshal\' SET mr = \'" + mrs.get(row) +
"\' , shop = \'" +shops.get(row)+ "\' where id = \'" + ids.get(row) + "\'";
ERROR:
SEVERE: null
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''alarm bell marshal' SET mr = '0' , shop = '0' where id = '1'' at line 1
try use something how that:
String sql = 'UPDATE `alarm bell marshal` SET `mr` = "' + mrs.get(row) + '" , `shop` = "' + shops.get(row) + '" WHERE `id` = "' + ids.get(row) + '"';

org.postgresql.util.PSQLException: ERROR: column "id" does not exist - Java Web Service

I am developing a java web service that is deployed in wildly. It is connected to a postgresql database.
In this database, I have a table called xx_activity. In it there is a column called "id", which is also the primary key.
Here is the query used to create the table:
CREATE TABLE xx_activity
(
id serial NOT NULL,
baseitemid integer
);
to connect to this table, I use the following java code:
conn = postgresVoyateDBConnection();
query = conn.prepareStatement("select id, baseitemid" +
"from xx_activity " +
"where \"id\" = ? ");
query.setInt(1, id);
ResultSet rs = query.executeQuery();
However, when I call the method that includes this code, I get an error:
org.postgresql.util.PSQLException: ERROR: column "id" does not exist
Position: 8
This is confusing because I certainly have this column. i added escape characters as per this answer, but it did not solve the issue.
Also note that queries without the where clause, like:
conn = postgresVoyateDBConnection();
query = conn.prepareStatement("select id, baseitemid " +
"from xx_activity");
ResultSet rs = query.executeQuery();
work perfectly.
I have also tried without using escape characters but it gives the same error. I also checked in pgadmin and there is no trailing space in the column name, neither are there any upper case letters involved (in which case, the other select query shouldn't have worked?).
How can this be fixed?
Fixed this, the issue was a missing space. After the first line of the query, there needs to be a space as belows:
query = conn.prepareStatement("select id, baseitemid " +
"from xx_activity " +
"where \"id\" = ? ");
EDIT: escape charactors not needed for id; so final answer should be:
query = conn.prepareStatement("select id, baseitemid " +
"from xx_activity " +
"where id = ? ");

JPA use IN clause with objects

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 !

Java and prepareStatement with MySQL

I use Java to do some SQL queries.
in general the queries that i want to perform are:
set #uid=?; set #friendsList=?; IF EXISTS(select 1 from fb_user_friends join fb_user on " +
" fb_user.id = fb_user_friends.fb_user_id where uid=#uid) then " +
"update fb_user_friends set friends = #friendsList; ELSE insert " +
"into fb_user_friends(fb_user_id,friends) values(#uid,#friendsList); END IF;
I get the MySQL Connection using:
Class.forName("com.mysql.jdbc.Driver").newInstance();
this._sqlconn = DriverManager.getConnection(this._url,this._userName,this._password);
and I try to execute the following code:
String sql="set #uid=?; set #friendsList=?; IF EXISTS(select 1 from fb_user_friends join fb_user on " +
" fb_user.id = fb_user_friends.fb_user_id where uid=#uid) then " +
"update fb_user_friends set friends = #friendsList; ELSE insert " +
"into fb_user_friends(fb_user_id,friends) values(#uid,#friendsList); END IF;";
try {
PreparedStatement stmt = this._sqlconn.prepareStatement(sql);
stmt.setLong(1,uid);
stmt.setString(2,StringUtils.join(friendsList.toArray(), ','));
stmt.executeUpdate();
}catch (SQLException e) ....
I get the exception:
class com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'set #friendsList='110633,2018837,6813007,8803501,10711399,500061635,500214841,50'
can't I run several commands with prepareStatement ?
Do i need to find a different approach to set the MySQL variables uid and friendsList?
Thanks!
That looks a bit like a mysql stored procedure to me? If I'm not mistaken, you should register that in mysql directly. That way, you're able to call it using your prepared statement.

Categories