如何 return c# 中 postgresql 函数的结果?控制台输出为空
How to return the result of a postgresql function in c#? Console output empty
我有一个问题,我在 postgresql 中有一个函数计算两个整数,并且应该 return 将结果发送到 c# (npgsql) conosle,我不知道我的错误在哪里,因为调试器没有对我说任何有用的东西。
所以首先是 c# 和函数的代码。
...
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
所以当我尝试 运行 它时,
Console.WriteLine(cmd.Parameters["sum"].Value);
将为空并且 ["sum"].Value 为 NULL。我究竟做错了什么?我说得对吗,当我说 "sum" 是一个 OUT 变量时,我不需要 return?
请帮忙。
已解决,谢谢大家! @Patrick 给了我正确的答案:
使用 ExecuteScalar() 而不是 ExecuteNonQuery()
您是否尝试过 运行 此代码,例如 command.ExecuteNonQuery() ?因为您正在读取一个值而没有实际执行查询。
connection.Open();
command.ExecuteNonQuery();
int result = (int) cmd.Parameters["sum"].Value;
Console.WriteLine(result);
而不是
command.ExecuteNonQuery();
你应该打电话给
Object res = command.ExecuteScalar();
Console.WriteLine(res);
我有一个问题,我在 postgresql 中有一个函数计算两个整数,并且应该 return 将结果发送到 c# (npgsql) conosle,我不知道我的错误在哪里,因为调试器没有对我说任何有用的东西。
所以首先是 c# 和函数的代码。
...
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
所以当我尝试 运行 它时,
Console.WriteLine(cmd.Parameters["sum"].Value);
将为空并且 ["sum"].Value 为 NULL。我究竟做错了什么?我说得对吗,当我说 "sum" 是一个 OUT 变量时,我不需要 return?
请帮忙。
已解决,谢谢大家! @Patrick 给了我正确的答案: 使用 ExecuteScalar() 而不是 ExecuteNonQuery()
您是否尝试过 运行 此代码,例如 command.ExecuteNonQuery() ?因为您正在读取一个值而没有实际执行查询。
connection.Open();
command.ExecuteNonQuery();
int result = (int) cmd.Parameters["sum"].Value;
Console.WriteLine(result);
而不是
command.ExecuteNonQuery();
你应该打电话给
Object res = command.ExecuteScalar();
Console.WriteLine(res);