.Net调用PostgreSQL简单存储过程时遭遇42601语法错误的问题求助
.Net调用PostgreSQL简单存储过程时遭遇42601语法错误的问题求助
嘿,我一眼就瞅出问题所在了——你写的CALL语句语法不对!
PostgreSQL里调用存储过程的CALL命令必须带括号,哪怕你打算用参数化传递参数,也得把括号加上,不然数据库会认为你的语法不完整,直接抛出42601这个语法错误。你现在的代码里写的是"CALL module.test",少了关键的括号和参数占位符,这就是报错的根源。
给你两种解决办法,选哪个都行:
方案一:修正CALL语句的格式
把NpgsqlCommand的SQL文本改成带括号和参数占位符的形式,比如:
using (var command = new NpgsqlCommand("CALL module.test(@pi_data, @po_data)", connection)) { var pin = command.Parameters.Add("pi_data", NpgsqlTypes.NpgsqlDbType.Integer); pin.Value = 2; pin.Direction = ParameterDirection.Input; var pout = command.Parameters.Add("po_data", NpgsqlTypes.NpgsqlDbType.Integer); pout.Direction = ParameterDirection.InputOutput; pout.Value = 8; command.ExecuteNonQuery(); }
这里的@pi_data和@po_data是命名参数,和你添加的参数名对应,PostgreSQL和Npgsql都能正确识别。
方案二:使用CommandType.StoredProcedure
更省心的方式是直接指定命令类型为存储过程,不用自己写CALL语句,让Npgsql帮你处理底层语法:
using (var command = new NpgsqlCommand("module.test", connection)) { command.CommandType = CommandType.StoredProcedure; // 关键是这一行 var pin = command.Parameters.Add("pi_data", NpgsqlTypes.NpgsqlDbType.Integer); pin.Value = 2; pin.Direction = ParameterDirection.Input; var pout = command.Parameters.Add("po_data", NpgsqlTypes.NpgsqlDbType.Integer); pout.Direction = ParameterDirection.InputOutput; pout.Value = 8; command.ExecuteNonQuery(); }
这种方式下,你只需要传入存储过程的全名module.test,Npgsql会自动生成符合PostgreSQL要求的CALL语句,完全避免语法格式问题。
另外再确认下:你的存储过程在pgAdmin里能正常运行,说明存储过程本身没问题,就是.Net代码里的调用语法没符合PostgreSQL的要求,按上面的方法改完应该就能正常执行了。
备注:内容来源于stack exchange,提问作者Wiizl
相关产品推荐
相关产品推荐

