JDBC Returning MySQLSyntaxError Exception Despite Correct Statement
When attempting to insert new rows into a MySQL table, a Java application encountered a MySQLSyntaxError Exception. Upon examining the SQL statement, it appeared syntactically correct. However, when executed directly using MySQL Workbench, the statement succeeded.
The code in question used a PreparedStatement to execute the INSERT statement, as seen below:
<code class="java">PreparedStatement sInserim = conn.prepareStatement(sqlCommandInserim); sInserim.setString(1, utente); sInserim.setString(2, nome); sInserim.executeUpdate(sqlCommandInserim);</code>
The exception encountered was:
<code class="text">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 '? , ? , DEFAULT , NULL )' at line 1</code>
Upon closer examination, it was revealed that the placeholders (?) were not being properly replaced by the PreparedStatement. This was evident from the following line:
<code class="java">sInserim.executeUpdate(sqlCommandInserim);</code>
The executeUpdate() method was being invoked with the raw SQL string as an argument, instead of using the PreparedStatement object with its set values.
To rectify the issue, the code was modified to:
<code class="java">sInserim.executeUpdate();</code>
By using executeUpdate() without a SQL string argument, the PreparedStatement's values are automatically used, resolving the MySQLSyntaxError Exception.
Note:
While not directly related to the stated problem, it is recommended to close the PreparedStatement (and any other resources, such as Connection, Statement, and ResultSet) in a finally block to prevent resource leaks in the event of exceptions.
The above is the detailed content of Why Does My Java Code Get a MySQLSyntaxError Exception Despite Using a PreparedStatement?. For more information, please follow other related articles on the PHP Chinese website!