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

和自甴很熟 提交于 2019-12-07 12:32:35

问题


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:


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



来源:https://stackoverflow.com/questions/1199134/how-can-i-provide-the-table-name-for-a-query-as-command-parameter-in-npgsql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!