chuwy
chuwy

Reputation: 6679

Check all placeholders in PreparedStatement are filled

I have a user-generated SQL-statement with placeholders (like SELECT * FROM films WHERE stars > ? AND length > ?) and arbitrary amount of inputs for values supposed to be inserted. I'm iterating through inputs to insert all of them into PreparedStatement, but I don't know on compile-time how many placeholders in PreparedStatement nor how many inputs user provided.

As far as I understand, supposed way to go is to catch SQLException on preparedStatement.execute(), which tells me that "no value specified for placeholder ...", but it doesn't work for me for many reasons:

Also searching for ? in generated query doesn't work because it will fail on following statement: SELECT * FROM films WHERE title = 'Who Framed Roger Rabbit?'

So, is there any way to check completeness of PreparedStatement before execution?

Upvotes: 1

Views: 1657

Answers (1)

nyname00
nyname00

Reputation: 2566

Take a look at java.sql.ParameterMetaData, it should contain all sorts of information on your PreparedStatement (including parameter count).

PreparedStatement pstmt = ...
ParameterMetaData metadata = pstmt.getParameterMetaData();
int pcount = metadata.getParameterCount();

pcount will contain the number of parameters. Note, that pstmt.getParameterMetaData() will connect to the database.

So when iterating your input and binding parameters you can assure (at runtime) that all parameters are bound.

Upvotes: 4

Related Questions