使用参数postgresql执行存储过程

时间:2017-09-08 09:13:27

标签: c# postgresql npgsql stored-functions

我的Npgsql版本3.2.5 - Postgresql 9.6

我在CommandType.StoredProcedure时收到此错误(但CommandType.Text有效):

  

Npgsql.PostgresException:' 42883:function customer_select(pEmail => text,Password => text)不存在'

string sql3 = @"customer_select";

NpgsqlConnection pgcon = new NpgsqlConnection(pgconnectionstring);
pgcon.Open();
NpgsqlCommand pgcom = new NpgsqlCommand(sql3, pgcon);
pgcom.CommandType = CommandType.StoredProcedure;
pgcom.Parameters.AddWithValue(":pEmail", "myemail@hotmail.com");
pgcom.Parameters.AddWithValue(":pPassword", "eikaylie78");
NpgsqlDataReader pgreader = pgcom.ExecuteReader();

while (pgreader.Read()) {
    string name = pgreader.GetString(1);
    string surname = pgreader.GetString(2);
}

这是数据库中的功能:

CREATE OR REPLACE FUNCTION public.customer_select(
    pemail character varying, ppassword character varying)
RETURNS SETOF "CustomerTest"
LANGUAGE 'plpgsql'
COST 100.0
AS $function$                                   
BEGIN 
    RETURN QUERY
        SELECT "CustomerTestId", "FirstName", "LastName", "Email", "Password"
        FROM public."CustomerTest"
        WHERE "Email" = pEmail AND "Password" = pPassword;
END; 
$function$;
ALTER FUNCTION public.customer_select(character varying, character varying)
OWNER TO postgres;

2 个答案:

答案 0 :(得分:1)

Npgsql确实支持命名参数,但您的参数'大小写与您的函数不匹配',请尝试pemail而不是pEmailppassword而不是pPassword。< / p>

请注意,使用CommandType.StoredProcedure而非CommandType.Text与Npgsql相比没有特别的优势 - 两者最终都做同样的事情。 CommandType.StoredProcedure主要是为了方便从SqlServer等移植代码。

答案 1 :(得分:0)

根据issue NPS SQL 不支持命名参数,因为PostgreSQL没有。但你可以试试以下:

string sql3 = @"select * from customer_select(:pEmail, :pPassword)";    
NpgsqlConnection pgcon = new NpgsqlConnection(pgconnectionstring);
pgcon.Open();
NpgsqlCommand pgcom = new NpgsqlCommand(sql3, pgcon);
pgcom.CommandType = CommandType.Text;
pgcom.Parameters.AddWithValue("pEmail", "myemail@hotmail.com");
pgcom.Parameters.AddWithValue("pPassword", "eikaylie78");
NpgsqlDataReader pgreader = pgcom.ExecuteReader();

while (pgreader.Read()) {
    string name = pgreader.GetString(1);
    string surname = pgreader.GetString(2);
}

根据此issue