Skip to content
Advertisement

Is that possible that access to a sql table with question mark?

I have 3 sql tables customer, employee and manager. I want to access dynamically to my tables. I had a statement like this,

"update customer set AMOUNT where ID= ?"

But in this situation i can only access to customer. I need to access all of the tables for different operations. Is that possible to write this,

"update ? set AMOUNT where ID=?"

or what can i do to access for example employee for a different class.

Advertisement

Answer

The parameters can be used only in the place where you could otherwise use a literal value, like a quoted string or a numeric value.

Parameters cannot be used for identifiers like table names. Nor expressions. Nor SQL keywords.

All those other parts of the query must be fixed in the SQL query string before you prepare the query.

To query other tables, you just have concatenate the table name into the string.

String query = "update " + tableName + " set amount where ID=?";

It’s up to you to make sure your variable tableName in fact only contains one of your table names. A good way to do this is to compare it to a list of known table names, and if it isn’t in the list, throw an exception.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement