I am wondering can i insert table name in this format
String update = "UPDATE ? SET Status = ? WHERE Name = ?";
stmt.setString(1,tableName);
stmt.setString(2,status);
stmt.setString(3,name);
same for insert and delete statements?
I am wondering can i insert table name in this format
String update = "UPDATE ? SET Status = ? WHERE Name = ?";
stmt.setString(1,tableName);
stmt.setString(2,status);
stmt.setString(3,name);
same for insert and delete statements?
No.
The reason you place question marks in the query (aside from protection against SQL injection) is so that the database can prepare the statement once and use that prepared statement with different parameters. It wouldn't be able to prepare a statement if it doesn't know what table(s) you are using.
The short answer is no. But you can do it this way:
String update = "UPDATE " + tableName + " SET Status = ? WHERE Name = ?";
...
stmt.setString(1,status);
stmt.setString(2,name);
Be aware of the SQL injection though. Be sure your tableName comes from the secure source.
Normally, you would do this as shown below...
String sql = "UPDATE " + tableName " SET Status = ? WHERE Name = ?";
PreparedStatement stmt = null;
try {
stmt = connection.prepareStatement(sql);
stmt.setString(1, status);
stmt.setString(2, name);
stmt.executeUpdate();
} finally {
if (stmt != null) {
stmt.close();
}
}
No you cann't do this because you are definitely using a prepared statement. The reason you can not do this is PreparedStatement is pre-compiled so it needs the table which you are modifing (its data using DML) or structurally (using DDL). If you don't mention the table table name how the statement is going to be pre-compiled?
If you want you can use dynamic SQL but in that case you don't have to use PreparedStatement you can use it using a simpler implementation Statement.
Hope this is helpful !!