简体   繁体   English

使用参数的npgsql语句

[英]statement for npgsql using parameter

I pass the parameters in the sql query using the driver npgsql: 我使用驱动程序npgsql在sql查询中传递参数:

SqlCommand = new NpgsqlCommand();
....
SqlCommand.CommandText = "SELECT id,name FROM table1 WHERE field1=:param2 ORDER BY name;";
SqlCommand.Parameters.AddWithValue("param2", 1);

This query executed correctly and issued the necessary data, but as soon as I add parameter to the sql in the section "select" 此查询正确执行并发出了必要的数据,但是只要我在“选择”部分中将参数添加到sql中,

SqlCommand.CommandText = "SELECT id,name :param1 FROM table1 WHERE field1=:param2 ORDER BY name;";
SqlCommand.Parameters.AddWithValue("param1", ",field1");
SqlCommand.Parameters.AddWithValue("param2", 1);

it gives me some kind of nonsense. 这给了我些废话。 In theory this request to the server is to be treated as 理论上,对服务器的此请求应被视为

SELECT id,name,field1 FROM table1 WHERE field1=1 ORDER BY name;

but it did not happen. 但是这没有发生。 This raises the question: is there a way to dynamically insert a list of fields using suchlike parameters? 这就提出了一个问题:是否有一种方法可以使用类似的参数来动态插入字段列表?

Unfortunately, Npgsql doesn't have support for what you are trying to do. 不幸的是,Npgsql不支持您尝试执行的操作。 NpgsqlParameter values are supposed to be only used as parameter values in the where clause. NpgsqlParameter值应该仅用作where子句中的参数值。 In order to add field names dynamically as you intend, you will have to create the query manually by using string concatenation. 为了按预期方式动态添加字段名称,您将必须使用字符串串联手动创建查询。

I hope it helps. 希望对您有所帮助。

Rewrite you CommandText and add this: 重写您的CommandText并添加以下内容:

foreach (NpgsqlParameter item in _Command.Parameters)
{
    comm.Parameters.AddWithValue(item.ParameterName, item.Value);
}

And solve your problem.. 并解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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