statement for npgsql using parameter

自作多情 提交于 2020-01-06 03:27:07

问题


I pass the parameters in the sql query using the driver npgsql:

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"

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?


回答1:


Unfortunately, Npgsql doesn't have support for what you are trying to do. NpgsqlParameter values are supposed to be only used as parameter values in the where clause. 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.




回答2:


Rewrite you CommandText and add this:

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

And solve your problem..



来源:https://stackoverflow.com/questions/24482569/statement-for-npgsql-using-parameter

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