Npgsql 7调用PostgreSQL表返回函数报错求助
Npgsql 7 调用PostgreSQL返回表函数的正确方式
方式一:位置参数匹配
当使用SELECT * FROM orders_daily_get($1,$2)的SQL语法时,需按顺序添加对应参数(对应$1、$2的位置),代码示例:
using NpgsqlConnection npgsqlConnection = new("conn_string"); using NpgsqlCommand cmd = new("SELECT * FROM orders_daily_get($1,$2)", npgsqlConnection); // 按SQL中$1、$2的顺序添加参数 cmd.Parameters.Add(new() { Value = Convert.ToDateTime("2023-07-01"), NpgsqlDbType = NpgsqlDbType.Date }); cmd.Parameters.Add(new() { Value = Convert.ToDateTime("2023-07-19"), NpgsqlDbType = NpgsqlDbType.Date }); npgsqlConnection.Open(); using NpgsqlDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { // 此处处理数据 } npgsqlConnection.Close();
方式二:命名参数调用
如果偏好使用命名参数,可在SQL中明确指定函数参数名,同时对应添加带命名的参数,代码示例:
using NpgsqlConnection npgsqlConnection = new("conn_string"); // 用:=指定函数参数和SQL参数的映射 using NpgsqlCommand cmd = new("SELECT * FROM orders_daily_get(p_startdate := @p_startdate, p_enddate := @p_enddate)", npgsqlConnection); // 参数名需与SQL中的@前缀名称对应 cmd.Parameters.Add(new() { ParameterName = "@p_startdate", Value = Convert.ToDateTime("2023-07-01"), NpgsqlDbType = NpgsqlDbType.Date }); cmd.Parameters.Add(new() { ParameterName = "@p_enddate", Value = Convert.ToDateTime("2023-07-19"), NpgsqlDbType = NpgsqlDbType.Date }); npgsqlConnection.Open(); using NpgsqlDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { // 此处处理数据 } npgsqlConnection.Close();
报错原因解析
你遇到的08P01: bind message supplies 0 parameters, but prepared statement "" requires 2错误,是因为SQL语句中声明了$1、$2两个参数,但未向NpgsqlCommand实例添加对应参数,导致数据库预期接收2个参数但实际未收到。
注:Npgsql 7 官方不再推荐使用CommandType.StoredProcedure调用PostgreSQL函数,建议直接通过SQL语句调用,避免兼容性问题。
内容的提问来源于stack exchange,提问作者user16479527
相关产品推荐
相关产品推荐

