I'm trying to use a PreparedStatement with code similar to this:
SELECT * FROM ? WHERE name = ?
Obviously, what happens when I use setString() to set the table and name field is this:
SELECT * FROM 'my_table' WHERE name = 'whatever'
and the query doesn't work. Is there a way to set the String without quotes so the line looks like this:
SELECT * FROM my_table WHERE name = 'whatever'
or should I just give it up and use the regular Statement instead (the arguments come from another part of the system, neither of those is entered by a user)?
Parameters cannot be used to parameterize the table, or parameterize any database objects. They're mostly used for parameterizing WHERE/HAVING clauses.
To do what you want, you'll need to do the substitution yourself and create a regular statement as needed.
When you use a prepared statement, this is a hint to the database to do up front processing on the statement - e.g. parse the string and possibly determine an execution plan. If the objects used in the query can change dynamically, then the database could not do much up front preparation.
Unfortunately you cannot parameterize table names for prepared statements. If desired, you could construct a String and execute it as dynamic SQL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With