问题
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 int this situation i can only access to customer. I need to access all of the tables for different operations. Is that possible that write this,
"update ? set AMOUNT where ID=?"
or what can i do to access for example employee for a different class.
回答1:
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.
来源:https://stackoverflow.com/questions/65544007/is-that-possible-that-access-to-a-sql-table-with-question-mark