tags:

views:

54

answers:

3

Using java.sql.Preparedstatement implies the escaping of characters will be done while parsing the queries, this does happen also when I have single quotes in my data but when I have single quotes in my table name itself the query does not work (I am using Oracle 11g).

Here's my code:

Class.forName("oracle.jdbc.OracleDriver");
con = DriverManager.getConnection(
    "jdbc:oracle:thin:client/adept@ind-db-02:1521:ind02");

PreparedStatement preparedStatement = con.prepareStatement(
    "SELECT * FROM (?) where rownum=1");

preparedStatement.setString(1,"CLIENT.\"SR'tab\"");
ResultSet rs3=preparedStatement.executeQuery();

Is there any way of escaping single quotes from the table name using a prepared statement?

+4  A: 

PreparedStatement placeholders are not intended for table names nor column names, they are only intended for actual column values. In other words, you are actually misusing PreparedStatement.

See also

Pascal Thivent
[Deja vu](http://stackoverflow.com/questions/3655615/sql-prepared-statment-to-create-table) and [here](http://stackoverflow.com/questions/1875049/preparedstatement-not-returning-ordered-resultset/1875136#1875136) :)
BalusC
@BalusC Yes, indeed, I confess :)
Pascal Thivent
A: 

hi!

Although it is very correct to use bind parameters to pass data to the database, you can not use bind parameters for table names.

In that case, it should be enought to properly quote it.

e.g. (untested):

PreparedStatement preparedStatement=
  con.prepareStatement("SELECT * FROM \"CLIENT.SR'tab\" where rownum=1"); 
Markus Winand
This does not work with proper quotes for the table name . i have tried that , reason i suspect for this escapeProcessing is on , when i disable escapeProcessing (JDBC level) + proper quoting then query works fine
sourabh
+1  A: 

I recommend you change those table names now, to prevent agony in the future. The high-powered tools we all use are great but when one colors too far outside the lines, the pain is unending.

Tony Ennis