Home > Database > Mysql Tutorial > body text

Why Does My Java Code Get a MySQLSyntaxError Exception Despite Using a PreparedStatement?

Susan Sarandon
Release: 2024-10-31 00:35:30
Original
252 people have browsed it

Why Does My Java Code Get a MySQLSyntaxError Exception Despite Using a PreparedStatement?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!