简体   繁体   中英

How can I provide the table name for a query as command parameter in Npgsql?

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM