Java and prepareStatement with MySQL - java

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.

Related

Got an exception! You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax

I got this error i am using java and javafx and it is connected to MYsql DB i got this error while excute this statment from java to my sql please help
Got an exception!
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 'update kstds.match SET
kstds.match.Team1Goals=kstds.match.Team1Goals+1 where kst' at line 1
String Query ="use kstds; update kstds.match SET kstds.match.Team1Goals=kstds.match.Team1Goals+1 "
+ "where kstds.match.Team1ID= ( select kstds.team.TeamID from kstds.team where kstds.team.Name='AHLI' ) "
+ "and kstds.match.Matchid = 1 ; "
+ "Update kstds.match SET kstds.match.Team2Goals=kstds.match.Team2Goals+1 "
+ "where kstds.match.Team2ID= ( select kstds.team.TeamID from kstds.team where kstds.team.Name='AHLI' ) "
+ "and kstds.match.Matchid=1;";
you are trying to execute multiple sql queries which should be done using addBatch & executeBatch.
you don't have to execute use kstds because the connection to the database is set via Java
try this:
String Query1 ="update match SET match.Team1Goals=match.Team1Goals+1 "
+ "where match.Team1ID= ( select team.TeamID from team where team.Name='AHLI' ) "
+ "and match.Matchid = 1 ; "
String Query2 ="Update match SET match.Team2Goals=match.Team2Goals+1 "
+ "where match.Team2ID= ( select team.TeamID from team where team.Name='AHLI' ) "
+ "and match.Matchid=1;";
//stmt is your Statement and conn is your Connection
con.setAutoCommit(false);
stmt.addBatch(Query1);
stmt.addBatch(Query2);
stmt.executeBatch();
con.commit();

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.

Update syntax error

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.

JDBC error but no error when I run my query in MySQL workbench

I am running a query on a MySQL database, I am using JDBC and I am using MySQL workbench to run the query.
When I run it in MySQL work bench I get what I was expecting but when I run it in my code I get.
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 'SELECT Character.CharacterID, Character.CharacterName, Characte' at line 1
Here is the Java:
for (int i = 0; i < 3; i++) {
try {
result = s.executeQuery("USE `arbitrary-hero`; SELECT `Character`.CharacterID, `Character`.CharacterName, `Character`.CharacterLevel, SUM(ItemAttack), SUM(ItemHealth), SUM(ItemAgility), "
+ "SUM(ItemStrength), SUM(ItemSource) FROM `arbitrary-hero`.`Character` INNER JOIN `arbitrary-hero`.Character_Items ON `Character`.CharacterID = Character_Items.CharacterID INNER JOIN "
+ "Items ON Character_Items.ItemID = Items.ItemID WHERE Character_Items.Equiped = 1 and `Character`.CharacterName = "+ name[i] +" GROUP BY `Character`.CharacterName;;");
}
catch(Exception e) {
System.out.println(e);
}
}
s.close();
Here is the SQL:
SELECT `Character`.CharacterID, `Character`.CharacterName, `Character`.CharacterLevel, SUM(ItemAttack), SUM(ItemHealth), SUM(ItemAgility), SUM(ItemStrength),
SUM(ItemSource) FROM `arbitrary-hero`.`Character` INNER JOIN `arbitrary-hero`.Character_Items ON
`Character`.CharacterID = Character_Items.CharacterID INNER JOIN Items ON
Character_Items.ItemID= Items.ItemID WHERE Character_Items.Equiped = 1 and `Character`.CharacterName = "Maxinfet" GROUP BY `Character`.CharacterName;
Not sure, but I think you can't use two SQL commands together, so everything after the semi-colon is an error.

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