MySQLSyntaxErrorException near “?” when trying to execute PreparedStatement

前端 未结 2 1025
星月不相逢
星月不相逢 2020-11-22 08:12

I\'m trying to execute a query using a PreparedStatement in Java.

I am getting error number 1064 when I try to execute my query (syntax error).

I have teste

相关标签:
2条回答
  • 2020-11-22 08:48

    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 '? or MemberName = ?' at line 1

    MySQL doesn't understand the meaning of ? in the SQL query. It's indeed invalid SQL syntax. So somehow it's not been replaced by PreparedStatement. And guess what?

    PreparedStatement s = conn.prepareStatement(query);
    s.setInt(1, intValue);
    s.setString(2, strValue);        
    rs = s.executeQuery(query); // Fail!
    

    You're overridding the prepared query with the original query! You need to call the argumentless PreparedStatement#executeQuery() method instead of Statement#executeQuery(String).

    PreparedStatement s = conn.prepareStatement(query);
    s.setInt(1, intValue);
    s.setString(2, strValue);        
    rs = s.executeQuery(); // OK!
    

    Unrelated to the problem, your code is leaking resources. The DB will run out of them after several hours and your application will crash. To fix this, you need to follow the JDBC idiom of closing Connection, Statement and ResultSet in the finally block of the try block where they're been acquired. Check the JDBC basic tutorial for more detail.

    0 讨论(0)
  • 2020-11-22 08:57

    If you look at the javadocs for Statement (the superclass of PreparedStatement), the method docs for executeQuery(String) and executeUpdate(String) say this:

    Note: This method cannot be called on a PreparedStatement or CallableStatement.

    That's what you are doing here: calling executeQuery(String) from Statement on a PreparedStatement object.

    Now since the javadocs say that you "cannot" do this, actual behavior you get is unspecified ... and probably JDBC driver dependent. In this case, it appears that the MySQL driver you are using is interpreting this to mean that you are doing the update as a non-prepared statement, so that the ? tokens are NOT interpreted as parameter placeholder. That leads the server-side SQL parser to say "syntax error".

    (It would be easier for programmers if a different unchecked exception was thrown by the MySQL driver if you did this; for example UnsupportedOperationException. However, the standard JDBC javadocs don't say what should happen in this situation. It is up to the vendor what their drivers will do.)

    0 讨论(0)
提交回复
热议问题