Skip to content
Advertisement

Query through PreparedStatement in H2 throws exception: This method is not allowed for a prepared statement; use a regular statement instead

A simple query fails when run through a prepared statement while using JDBC 4 to access an H2 database in Java 11.

When running this line:

…I get this error:

org.h2.jdbc.JdbcSQLException: This method is not allowed for a prepared statement; use a regular statement instead. [90130-197]

I tried using the H2 Error Analyzer, but no help there.

Here is a complete example app, in a single .java file. You can copy-paste and run yourself.

Exception reported:

Advertisement

Answer

Passing the SQL string twice

On a PreparedStatement, you never pass the SQL string to executeQuery method. You do so in an unprepared Statement, but not PreparedStatement. Notice how the JavaDoc for PreparedStatement::executeQuery takes no argument.

So your line:

…should be:

You already passed the SQL string named sql above that line, when you prepared the statement:

Since the PreparedStatement named pstmt already holds your SQL statement(s), there is no need to pass into executeQuery.

This mistake might have been the result of copy-pasting some code using Statement for reuse in some other code using PreparedStatement.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement