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
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(); }
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!