使用参数执行存储过程postgresql

5

我的Npgsql版本是3.2.5 - Postgresql 9.6。

在使用CommandType.StoredProcedure时,我遇到了这个错误(但CommandType.Text可以正常工作):

Npgsql.PostgresException: '42883:函数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;

1
提供详细的错误信息。 - slesh
函数customer_select(pEmail => text, pPassword => text)不存在发生了Npgsql.PostgresException异常 HResult=0x80004005 Message=42883: 函数customer_select(pEmail => text, pPassword => text)不存在 Source=Npgsql StackTrace: at Npgsql.NpgsqlConnector.<DoReadMessage>d__148.MoveNext() at - Korkut Düzay
2个回答

3
Npgsql支持命名参数,但是您的参数大小写与函数不匹配,请尝试使用pemail替代pEmailppassword替代pPassword
请注意,使用CommandType.StoredProcedureCommandType.Text在Npgsql中没有特别的优势-它们最终都会执行相同的操作。 CommandType.StoredProcedure主要是为了方便从SqlServer等移植代码。

我修正了参数名称(从pEmail改为pemail),并且当我使用“CommandType.StoredProcedure”时,它可以工作!谢谢。 - Korkut Düzay

2
根据问题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);
}

根据这个 问题

pgcom.CommandType = CommandType.Text; 这段代码可以正常工作。 - Korkut Düzay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接