如何在c#中返回postgresql函数的结果?控制台输出为空 [英] How to return the result of a postgresql function in c#? Console output empty
问题描述
我有一个问题,我在 postgresql 中有一个计算两个整数的函数,应该将结果返回到 c# (npgsql) 控制台,我不知道我的错误在哪里,因为调试器没有对我这有帮助.
I have the problem that i have a function in postgresql that calculates two integer and should return the result to the c# (npgsql) conosle and i don't know where my mistake is, because the debugger doesn't say anything to me which is helpful.
所以首先是 c# 和函数的代码.
so first of all the code of c# and of the function.
...
cmd.Parameters["x"].Value = 20;
cmd.Parameters["y"].Value = 22;
connection.Open();
if (connection.State == System.Data.ConnectionState.Open) {
//Console.WriteLine(cmd.Parameters["x"].Value);
command.ExecuteNonQuery();
Console.WriteLine(cmd.Parameters["sum"].Value);
}
现在是数据库的代码:
CREATE OR REPLACE FUNCTION t2(
IN x integer,
IN y integer,
OUT sum integer)
RETURNS integer AS
$BODY$BEGIN
sum := x + y;
INSERT INTO t2 (x, y, sum) values (x, y, sum);
END
所以当我尝试运行它时,
So when i try to run it,
Console.WriteLine(cmd.Parameters["sum"].Value);
将为空且 ["sum"].Value 为 NULL.我究竟做错了什么?我说的对,当我说sum"是一个 OUT 变量时,我不需要返回?
will be empty and the ["sum"].Value is NULL. What am I doing wrong? Am I right, that when I say that "sum" is an OUT variable, I do not need a return?
请帮忙.
解决了,谢谢大家!@Patrick 给了我正确的答案:使用 ExecuteScalar() 而不是 ExecuteNonQuery()
SOLVED, thank you to all! @Patrick gave me the right answer: use ExecuteScalar() instead of ExecuteNonQuery()
推荐答案
代替
command.ExecuteNonQuery();
你应该打电话
Object res = command.ExecuteScalar();
Console.WriteLine(res);
这篇关于如何在c#中返回postgresql函数的结果?控制台输出为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!