Home > Database > Mysql Tutorial > Why Am I Getting a 'Syntax error near '?'' with MySQL PreparedStatements?

Why Am I Getting a 'Syntax error near '?'' with MySQL PreparedStatements?

Patricia Arquette
Release: 2024-12-11 12:46:15
Original
595 people have browsed it

Why Am I Getting a

Exception Near "?" When Executing PreparedStatement in MySQL

In Java, when executing a query using PreparedStatement, one might encounter a MySQLSyntaxErrorException with error number 1064 indicating a syntax error near "?". This may occur even though the query works in a MySQL query browser with substituted values.

Upon closer examination, it becomes evident that MySQL is unable to interpret the "?" placeholder in the SQL query, deeming it invalid syntax. This is because PreparedStatement has not replaced these placeholders.

The code snippet you shared erroneously overwrites the prepared query with the original version. To rectify this, use PreparedStatement#executeQuery() instead of Statement#executeQuery(String):

PreparedStatement s = conn.prepareStatement(query);
s.setInt(1, intValue);
s.setString(2, strValue);        
rs = s.executeQuery(); // Correct
Copy after login

Note: While not related to the current issue, your code fails to close the Connection, Statement, and ResultSet. This omission can lead to resource exhaustion and subsequent application crash. Implement the proper JDBC idiom by closing these objects within a finally block:

try (Connection conn = DriverManager.getConnection(...);
     PreparedStatement s = conn.prepareStatement(...);
     ResultSet rs = s.executeQuery()) {
     // Query execution code
} finally {
     if (rs != null) rs.close();
     if (s != null) s.close();
     if (conn != null) conn.close();
}
Copy after login

The above is the detailed content of Why Am I Getting a 'Syntax error near '?'' with MySQL PreparedStatements?. 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