Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PreparedStatement.setString() method without quotes [duplicate]

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)?

like image 419
Slavko Avatar asked May 26 '10 23:05

Slavko


2 Answers

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.

like image 61
mdma Avatar answered Sep 21 '22 18:09

mdma


Unfortunately you cannot parameterize table names for prepared statements. If desired, you could construct a String and execute it as dynamic SQL.

like image 35
Aaron Silverman Avatar answered Sep 21 '22 18:09

Aaron Silverman