相关疑难解决方法(0)

如何在Npgsql中将查询的表名作为命令参数提供?

我想提供查询的表名作为命令参数,如下所示:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这似乎导致了这个查询:"SELECT * from E'mytable'"导致错误(请注意单引号).

我真的需要为此进行字符串连接吗?从安全角度来看并不重要,因为用户不能更改表名,但创建SQL查询的字符串连接总是让我感到毛骨悚然......

谢谢,埃里克

.net c# sql postgresql npgsql

3
推荐指数
1
解决办法
1555
查看次数

标签 统计

.net ×1

c# ×1

npgsql ×1

postgresql ×1

sql ×1