I am using JDBC for connecting to the database (Oracle10) in Servlets.
Following is my query in which I want to set the three parameters dynamically.
Query:
query = "select ? from ? where ? = ?";
mypstmt = con.prepareStatement(query);
mypstmt.setString(1, tableName);
mypstmt.setString(2, columnName);
mypstmt.setString(3, columnName2);
mypstmt.setString(4, value);
But above query is giving me error:
java.sql.SQLException: ORA-00903: invalid table name
I checked the table name. it is correct, and if I write the query like:
query = "select "+columnName+" from "+tableName+" where "+columnName2+" = ?";
Then it is executing fine.
So what should I do if I want to set the Table name and Column Names as mypstmt.setString(1,tableName)
Edit1
The reason why I want to parameterize the Table name and Column name is that I am allowing user to Select/Enter Table names and column names, so I want to avoid SQL Injection.
We can't pass the tablename directly to PreparedStatement as table name cannot be a bind variable . PreparedStatement.
An object that represents a precompiled SQL statement.
A SQL statement is precompiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times.
You have to construct the sql with string concatenation. Using Stored Procedure , you can pass table name dynamically using Dynamic SQL. Even look at this SO answer to understand why it is restricted.
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