3

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.

  1. Table name
  2. Column name
  3. Value

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.

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Column names can be passed as parameters using PreparedStatement?
@Polppan - no. Only values can be passed as parameters. (Otherwise, the SQL engine would not be able to precompile/plan prepared statements, and you'd have more scope for injection attacks, etc.)
3

you can only parameterized ? column value in SQL query. Table/Column parametrizing is not possible, instead use variable to construct such query, for example :

void query(String tableName, String columnName, String queryColumnName String val) {
String query = "select "+columnName+" from "+tableName+" where "+queryColumnName+" = ?";
mypstmt.setString(1, val);
..
}

Comments

1

In PreparedStatement you can only replace value. You cann't replace tablename, or column name.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.