views:

84

answers:

1

I want to provide the table name for a query as command parameters, like so:

public class Foo
{
    private const String myTableName = "mytable";

    public void Bar()
    {
        NpgsqlCommand command = new NpgsqlCommand("SELECT * from :tableName", connection);
        command.Parameters.Add(new NpgsqlParameter("tableName", DbType.String));
        command.Parameters[0].Value = myTableName;
    }
}

This seems to result in this query: "SELECT * from E'mytable'" which results in an error (mind the single quotes).

Do I really need to do string concatenation for this? It doesn't matter from a security standpoint, since the table name can not be changed by the user but string concatenation for creating SQL queries always gives me the creeps...

Thanks, Eric

+1  A: 

Table names cannot be sent as parameters. The table names are resolved at parse time, since they are needed for planning and such things. Parameters are only substituted at executor (or optimizer if necessary) time.

So yeah, you will need to use string replacement for it. It's not a security issue (or even the risk of becoming one) as long as the table name comes from a const in your class, of course.

But if you do construct the table name from user input, you need to be very careful. But usually if you need to construct the table name from user input, something is badly designed in the database in the first place and should be fixed (yes, there are of course exceptions to that).

Magnus Hagander
The table names are always constants. Thanks.
EricSchaefer