简体   繁体   中英

statement for npgsql using parameter

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?

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.

Rewrite you CommandText and add this:

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

And solve your problem..

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