Why this PreparedStaement throws a mysql error? [duplicate] - java

This question already has answers here:
MySQLSyntaxErrorException near "?" when trying to execute PreparedStatement
(2 answers)
Closed 3 years ago.
I am doing an insertion in a mysql database through a jdbc connection, which connects perfectly, that if when I do the PreparedStatement, Tomcat throws me a sql error that says the following:
java.sql.SQLSyntaxErrorException: 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 '?,?,?)' at line 1
The question is that when I do the query through a statement, it performs the query without any problem, which makes me suspect that the error is actually in the PreparedSatement. Here I leave the code.
#Override
public void save(Planet planet) throws SQLException {
String namePlanet = planet.getName();
float massPlanet = planet.getMass();
boolean habitablePlanet = planet.isHabitable();
sql = "INSERT INTO planeta (nom,massa,habitable) VALUES (?,?,?)";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, namePlanet);
preparedStatement.setFloat(2, massPlanet);
preparedStatement.setBoolean(3, habitablePlanet);
preparedStatement.executeUpdate(sql);
}
I will also leave the code with the preparedstatement, so you can see that this does work.
#Override
public void save(Planet planet) throws SQLException {
String namePlanet = planet.getName();
float massPlanet = planet.getMass();
boolean habitablePlanet = planet.isHabitable();
sql = "insert into planeta(nom,massa,habitable) value('" + namePlanet + "'," + massPlanet + "," + habitablePlanet + ")";
stmt.executeUpdate(sql);
}
Please be patient with me, I'm a student and thanks in advance.

Like #Jens told in the comments i have to call executeUpdate() without parameters.
Thx again #Jens!!
Thats the correct code:
#Override
public void save(Planet planet) throws SQLException {
String namePlanet = planet.getName();
float massPlanet = planet.getMass();
boolean habitablePlanet = planet.isHabitable();
sql = "INSERT INTO planeta (nom,massa,habitable) VALUES (?,?,?)";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, namePlanet);
preparedStatement.setFloat(2, massPlanet);
preparedStatement.setBoolean(3, habitablePlanet);
preparedStatement.executeUpdate(); // <--- Here was the error!!
}

Related

Getting error "statement.executeupdate() cannot issue statements that produce result sets." when trying to insert into mysql using JDBC

I'm trying to get the primary auto incremented key from one table and store this in another using MySQL connector and JDBC. Although its giving me this error:
statement.executeupdate() cannot issue statements that produce result
sets.
I think its something to do with the storing of the integer variable but not too sure.
public void insertIntoWorkoutLogs(String field_setNumber, String field_repNumber, String field_weightAmount) {
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/workout","root","");
Statement statement =connection.createStatement();
String insert ="INSERT INTO `workout`.`workoutlogs`" + " (`SetNumber`, `RepNumber` , `WeightAmount`)"
+ "VALUES('" +field_setNumber+"','"+field_repNumber+"','"+field_weightAmount+"')";
statement.executeUpdate(insert);
int workoutID = insertQueryGetId("SELECT workoutID FROM workout");
String insert2 ="INSERT INTO `workout`.`workoutlogs`" + " (`WorkoutID`)"
+ "VALUES('" +workoutID+"')";
statement.executeUpdate(insert2);
connection.close();
}catch(Exception e) {
System.out.println(e);
}
}
public int insertQueryGetId(String query) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/workout","root","");
Statement statement =connection.createStatement();
int workoutID=0;
int result=-1;
try {
workoutID = statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = statement.getGeneratedKeys();
if (rs.next()){
result=rs.getInt(1);
}
rs.close();
statement.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
I've tried using statement for this, but I'm thinking it may have to be prepared statement for it to work. Expecting to store the auto incremented primary key of one table (workouts) into a field within another table (workoutlogs).
It's because you are passing wrong query. Statement.RETURN_GENERATED_KEYS works with Insert queries not with Select queries.
When you insert a row in database, an auto increment value gets generated and is returned but you are passing a Select statement
As Syed Asad Manzoor said, it will work for you but then you need to remove Statement.RETURN_GENERATED_KEYS and statement.executeQuery() has return type of ResultSet so you need to store the result in ResultSet only.
public void insertIntoWorkoutLogs(String field_setNumber, String field_repNumber, String field_weightAmount) {
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/workout","root","");
Statement statement =connection.createStatement();
String insert ="INSERT INTO `workout`.`workoutlogs`" + " (`SetNumber`, `RepNumber` , `WeightAmount`)"
+ "VALUES('" +field_setNumber+"','"+field_repNumber+"','"+field_weightAmount+"')";
statement.executeUpdate(insert);
**int workoutID = insertQueryGetId("SELECT workoutID FROM workout");** // Line of Concern 1
String insert2 ="INSERT INTO `workout`.`workoutlogs`" + " (`WorkoutID`)"
+ "VALUES('" +workoutID+"')";
statement.executeUpdate(insert2);
connection.close();
}catch(Exception e) {
System.out.println(e);
}
}
public int insertQueryGetId(String query) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/workout","root","");
Statement statement =connection.createStatement();
int workoutID=0;
int result=-1;
try {
// Line of Concern 2
**workoutID = statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);**
In line (marked as Line of Concern 1 ..
int workoutID = insertQueryGetId("SELECT workoutID FROM workout"); you are passing query as "SELECT...." and at point marked as Line of Concern 2
workoutID = statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS); you are using executeUpdate.. thats why exception is thrown.
Change statement.executeUpdate(query) to statement.executeQuery(query)..
The INSERT statement needs to have flag RETURN_GENERATED_KEYS.
Then getting the ResultSet would deliver for every insert record the generated key(s).
Also use a PreparedStatement for escaping of strings and against SQL injection.
Use try-with-resources to automatically close the several objects, even with exception or early return.
Class.forName("com.mysql.cj.jdbc.Driver");
try (Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/workout", "root", "")) {
String insertSql = "INSERT INTO `workout`.`workoutlogs`"
+ " (`SetNumber`, `RepNumber` , `WeightAmount`)"
+ " VALUES(?, ?, ?)";
try (PreparedStatement statement = connection.prepareStatement(insertSql,
Statement.RETURN_GENERATED_KEYS)) {
statement.setString(field_setNumber);
statement.setString(field_repNumber);
statement.setBigDecimal(field_weightAmount);
statement.executeUpdate();
try (ResultSet rs = statement.getGeneratedKey()) {
if (rs.next()) {
int workoutID = rs.getInt(0);
//... second insert here
}
}
}
}

How to Fix MySQL Count Function Error In Java? [duplicate]

This question already has answers here:
How to use a tablename variable for a java prepared statement insert [duplicate]
(4 answers)
Closed 6 months ago.
I am trying to create a method that will count the number of records I have in a certain table when the method is called. But for some reason, I keep getting an error saying I have a problem in my SQL code. Looking over everything, I couldn't find the problem. I even went as far to as to copy parts of another person's solution online, but this failed too. To better show where the error seems to be ocurring, I inserted two print statements in the code. I think Java and SQL must hate me! Any help would be most appreciated.
int tableCounter(String tableName) {
int num = 0;
String sql = "SELECT COUNT(*) AS total FROM ?";
try(Connection conn = letConnect(); PreparedStatement ps = conn.prepareStatement(sql)){
ps.setString(1, tableName);
System.out.println("test");
ResultSet rs = ps.executeQuery();//error ocurrs here
//when the SQL code is executed
System.out.println("test");
num = rs.getInt("total");
} catch (SQLException e) {
e.printStackTrace();
}
return num;
}
Output:
test
java.sql.SQLSyntaxErrorException: 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 ''Country'' at line 1
at mysql.connector.java#8.0.30/com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at mysql.connector.java#8.0.30/com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at mysql.connector.java#8.0.30/com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:916)
at mysql.connector.java#8.0.30/com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:972)
at Database_Interactor.tableCounter(Database_Interactor.java:25)
at MainClass.main(MainClass.java:10)
Based on the answer given above, the code should look something like this:
int tableCounter(String tableName) {
int num = 0;
String sql = "SELECT COUNT(*) AS total FROM "+ tableName;
Connection conn = letConnect();
try{Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()){
num = rs.getInt("total");}
}catch (SQLException e) {
e.printStackTrace();}
return num;}

JAVA JDBC mySql Prepared statement Update query [duplicate]

This question already has answers here:
MySQLSyntaxErrorException near "?" when trying to execute PreparedStatement
(2 answers)
Closed 4 years ago.
I am trying to execute the following code
package jdbclesson;
import java.sql.*;
public class PreparedQuery {
public static void main(String[] args) throws Exception
{
String url = "jdbc:mysql://localhost:3306/alien?useSSL=false";
String uname = "root";
String pass = "ma123";
String query = "UPDATE student SET username= ? where userid= ? ";
PreparedStatement stmt = null;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, uname, pass);
stmt = con.prepareStatement(query);
stmt.setString(1, "tina");
stmt.setInt(2, 6);
int rs = stmt.executeUpdate(query);
System.out.println(rs);
stmt.close();
con.close();
}
}
but getting following errors
Exception in thread "main"
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 '? where
userid=?' at line 1
My database has only 1 table student with 2 columns userid and username and 10 rows what m i missing
Try:
int rs = stmt.executeUpdate();
Instead of:
int rs = stmt.executeUpdate(query);
executeUpdate() runs the query of the prepared statement, which is what you want. executeUpdate(query) runs the query passed to the method. You were getting the error because you were passing an SQL with errors (contains ?).
Please try:
"UPDATE student SET username= ? ” + ” where userid= ?";
int rs=stmt.executeUpdate();

PreparedStatement MySQLSyntaxErrorException using valid query string [duplicate]

This question already has answers here:
mysql prepared statement error: MySQLSyntaxErrorException
(2 answers)
Closed 8 years ago.
I've spent hours looking at what seems like what should be perfectly working code. The connection.createStatement() version of this method works fine but as soon as I try to convert it over to the better, connection.prepareStatement() version it throws a MySQLSyntaxErrorException and complains about a problem near the '?' character in my query string. The code is posted below and I simply cannot see the problem with it. The database field is VARCHAR and accepts Strings so that is not the problem.
public Discussion getDbDiscussionInstance(String _instanceId) throws SQLException {
String qryStr = null;
PreparedStatement myStmt = null;
ResultSet myRs = null;
// Try to build the object with existing data.
try {
qryStr = "SELECT assignment_id, discussion_id, section_id, user_id, circle_id, breakout_id, title, description, created, due FROM macb_discussions WHERE instance_id=?";
myStmt = connection.prepareStatement(qryStr);
myStmt.setString(1, _instanceId);
myRs = myStmt.executeQuery(qryStr);
if (rs.next()) {
this.discussionId = myRs.getString("discussion_id");
}
} catch (SQLException e) {
dbFunc.catchSQLException(e);
} finally {
myRs.close();
myStmt.close();
}
}
Use only myStmt.executeQuery(); without the argument, you have already preperad the statement
From the docs,
Statement.executeQuery(String sql)
PreparedStatement.executeQuery()
So change your function accordingly.
myStmt = connection.prepareStatement(qryStr); to
myStmt = connection.prepareStatement();

prepareStatement doesn't work with sqlite

I try to use prepareStatement to query an sqlite but I encounter an exception:
java.sql.SQLException: not supported by PreparedStatment
at org.sqlite.PrepStmt.unused(PrepStmt.java:328)
at org.sqlite.PrepStmt.executeUpdate(PrepStmt.java:314)
I'm developing my program using Eclipse, so when I click on at org.sqlite.PrepStmt.unused(PrepStmt.java:328) it redirects me to PrepStmt.class that inside it I found these:
#Override
public int executeUpdate(String sql) throws SQLException {
throw unused();
}
private SQLException unused() {
return new SQLException("not supported by PreparedStatment");
}
This is my code :
public static void deleteOp(String word) throws Exception {
Connection c = null;
PreparedStatement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection(connectionString);
c.setAutoCommit(false);
System.out.println("Opened database successfully");
String sql = "DELETE from " + tableName + " where WORD = ? ;";
System.out.println(sql);
stmt = c.prepareStatement(sql);
stmt.clearParameters();
stmt.setString(1, word);
stmt.executeUpdate(sql);
c.commit();
stmt.close();
c.close();
} catch ( Exception e ) {
throw e;
}
System.out.println("Operation done successfully");
}
I want to know is something wrong in my code or Sqlite doesn't support prepareStatement at all or there is a problem with my driver (for example due to being obsolete)?
You don't need to pass sql variable to executeUpdate method since you have configured it on prepareStatement sentence, so just try:
stmt.executeUpdate();
PreparedStatement lives a bit of a double life: it extends Statement, and thus inherits that class' methods — even though some of them don't really make much sense for PreparedStatement.
In this case, executeUpdate(String) comes from Statement and runs a statement straight-up, without doing the ? substitutions. It's not what you want: you want just executeUpdate(), which is the PreparedStatement variant. So in some sense, they're actually doing you a favor by not implementing the Statement variant!

Categories