简体   繁体   English

用Java调用PostgreSQL存储过程返回null

[英]Call PostgreSQL stored procedure with Java returns null

I have the following stored procedure written in PostgreSQL 9.3 that's working perfectly: 我有以下用PostgreSQL 9.3编写的存储过程,它们运行良好:

CREATE OR REPLACE FUNCTION getColor(i INT) 
 RETURNS VARCHAR AS $varColor$
    DECLARE varColor varchar;   
    BEGIN
      select color into varColor FROM colors where id = i;
      return varColor;
    END;
    $varColor$ LANGUAGE plpgsql;

In fact, when I execute select getColor(2) in pgAdmin I get the expected value. 实际上,当我在pgAdmin中执行select getColor(2) ,我得到了预期的值。 I am trying to call it like this from Java (simplified version): 我试图从Java(简化版)中这样称呼它:

String call =  "{ call getColor(?,?) }";
CallableStatement cstmt = connection.prepareCall(call);
cstmt.setInt(1, 2);
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR);
boolean hadResults = cstmt.execute();

The problem is that hadResults is always null. 问题是hadResults始终为null。 Any ideas? 有任何想法吗?

Postgresql stored procedures concept is something different than other vendors like Oracle. PostgreSQL存储过程的概念与其他供应商(如Oracle)有所不同。 Basically what in Oracle is called store procedure in Postgresql can be a function, and to call a function in Java is better to use prepare statements and executeQuery methods like in the following example 基本上,在Oracle中所谓的Postgresql中的存储过程可以是一个函数,而在Java中调用一个函数最好使用prepare语句和executeQuery方法,如以下示例所示

String call =  "select getColor(?)";
PreparedStatement pstmt = connection.prepareStatement(call);
pstmt.setInt(1,1);
Resultset resultset = pstmt.executeQuery();

Thank you to all the guys who helped in the question comments! 感谢所有在问题评论中提供帮助的人!

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

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