Skip to content
Advertisement

SQL error syntax, please check the manual that corresponds to your MariaDB server version for the right syntax to use

I try to insert a new value into a table by using preparedStatement but I obtain a syntax error that I can’t solve.

Java code :

String sql2 = "INSERT INTO Repondre VALUES ( ?, ?, ?, ?)";
preparedStatement = connection.prepareStatement(sql2);
preparedStatement.setInt(1, 1);
preparedStatement.setInt(2, 1);
preparedStatement.setInt(3,resultSet.getInt(1));
RadioButton rb = (RadioButton)q1.getSelectedToggle();
preparedStatement.setString(4,rb.getText().toLowerCase());
preparedStatement.executeUpdate(sql2);

Error Code :

java.sql.SQLSyntaxErrorException: 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 '?, ?, ?, ?)' at line 1

I hope that you can help me thank you.

Advertisement

Answer

I see several potential problems here. First, you are passing the SQL string to executeUpdate(), which is incorrect. It is wrong because the version of that method you want to call is for prepared statements, and it does not take any input parameters (you are calling the Statement version). Second, you neglected to list the columns which you want to target in your table for the inserted data. In general, you should always explicitly list all columns in an insert. Putting both of these together, we can try the following corrected version:

String sql = "INSERT INTO Repondre (col1, col2, col3, col4) VALUES (?, ?, ?, ?)";
PreparedStatement ps = connection.prepareStatement(sql2);
ps.setInt(1, 1);
ps.setInt(2, 1);
ps.setInt(3, resultSet.getInt(1));
RadioButton rb = (RadioButton)q1.getSelectedToggle();
ps.setString(4, rb.getText().toLowerCase());
preparedStatement.executeUpdate();   // NO parameters here

Note: Explicitly listing the columns is important because you want to insert your data in the right place. Sometimes, it would be possible to not list the columns, and by chance the data you mention would happen to all have the same type. This could lead to a subtle bug.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement