繁体   English   中英

PostgreSQL CallableStatement:无效的参数数量错误

[英]CallableStatement PostgreSQL :Invalid number of parameters error

我试图在PostgreSQL中编写示例存储函数,并使用JDBC提供的CallableStatement对其进行调用。

这是我的一些测试代码

Consumer bean =new Consumer();
CallableStatement pstmt = null;
try {
con.setAutoCommit(false);
String  query = "{ ? = call getData( ? ) }";
pstmt = con.prepareCall(query); 
 pstmt.registerOutParameter(1, Types.OTHER);
      pstmt.setInt(2,5);
      pstmt.execute(); // execute update statement
      bean=(Consumer)pstmt.getObject(1);
       System.out.println("bean"+bean.getConsumer_name());

我的存储函数的形式为。

CREATE FUNCTION getData(int) RETURNS SETOF db_consumer AS $$
 SELECT * FROM db_consumer WHERE consumer_id = $1;
$$ LANGUAGE SQL;

但是,尝试运行代码时出现以下错误。

org.postgresql.util.PSQLException: A CallableStatement was executed with an invalid    number of  parameters .

知道为什么会这样吗?

我认为您不需要CallableStatement,因为您应该能够直接运行select * from getData(5)

PreparedStatement pstmt = con.prepareStatement("select * from getData(?)")
pstmt.setInt(1,5);
ResultSet rs = pstmt.execute(); 
while (rs.next()) {
  System.out.println(rs.getString(1));
}

您试图通过可调用语句调用SETOFF函数。 那不会发生! 您总是会得到一个错误。

PostgreSQL的存储函数可以两种不同的方式返回结果。 该函数可以返回refcursor值或SETOF一些数据类型。 根据使用哪种返回方法,确定应如何调用该函数。
返回数据为一组的函数不应通过CallableStatement接口调用,而应使用常规的Statement或PreparedStatement接口。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM