0

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?

vijay
  • 1,129
  • 7
  • 22
  • 34
  • 6
    did you try it? – Dreamwalker Mar 13 '13 at 12:30
  • 3
    No, You cannot paramerize the table name. Use Dynamic SQL – Joe2013 Mar 13 '13 at 12:31
  • you can but only using dynamic SQL which this isn't doing. dynamic SQL does open you to SQL injection if you're not careful. – xQbert Mar 13 '13 at 12:31
  • If you need this, I suspect that the data structure is not properly done... Not sure, as I can't see what you have nor what you are trying to achieve, but if you have to replicate the exact same query over so many tables you'd like to have a generic prepared statement for it, there might be something bad going on... – ppeterka Mar 13 '13 at 12:35
  • thank you, i tried and failed now – vijay Mar 13 '13 at 12:43
  • possible duplicate of [Can PHP PDO Statements accept the table name as parameter?](http://stackoverflow.com/questions/182287/can-php-pdo-statements-accept-the-table-name-as-parameter) – david strachan Feb 27 '14 at 20:56

4 Answers4

5

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.

StuPointerException
  • 7,117
  • 5
  • 29
  • 54
3

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.

Boris Brodski
  • 8,425
  • 4
  • 40
  • 55
1

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();
        }
    }
David
  • 19,577
  • 28
  • 108
  • 128
0

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 !!

GKP
  • 1,057
  • 1
  • 11
  • 24