Home > Database > Mysql Tutorial > body text

Why Does My PreparedStatement Throw a Syntax Error Near \'?\': A Java MySQL Issue

Susan Sarandon
Release: 2024-11-19 17:32:03
Original
419 people have browsed it

Why Does My PreparedStatement Throw a Syntax Error Near

PreparedStatement Syntax Error: '<' Expected

Encountering the "preparedStatement syntax error" while using Java PreparedStatements can be frustrating. If you're encountering the error:

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 '?)' at line 1
Copy after login

with code like:

    String selectSql1
        = "SELECT `value` FROM `sampling_numbers` WHERE `value` < (?)" ;
    ResultSet rs1 = con.select1(selectSql1,randNum);
Copy after login

it's because you're incorrectly calling Statement.executeQuery(String) instead of PreparedStatement.executeQuery(). Here's how to fix it:

    this.stmt = con.prepareStatement(sql); // Prepares the Statement.
    stmt.setInt(1, randNum);               // Binds the parameter.
    // return this.stmt.executeQuery(sql); // calls Statement#executeQuery
    return this.stmt.executeQuery();       // calls your prepared PreparedStatement
Copy after login

By changing this line, you'll correctly execute the PreparedStatement and avoid the "preparedStatement syntax error."

The above is the detailed content of Why Does My PreparedStatement Throw a Syntax Error Near \'?\': A Java MySQL Issue. 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